developer tip

특정 속성이 설정된 요소에만 querySelectorAll을 사용하는 방법은 무엇입니까?

optionbox 2020. 9. 5. 09:44
반응형

특정 속성이 설정된 요소에만 querySelectorAll을 사용하는 방법은 무엇입니까?


속성이 설정된 document.querySelectorAll모든 확인란 에 사용하려고합니다 value.

페이지에 value설정 되지 않은 다른 확인란이 있으며 각 확인란의 값이 다릅니다. 하지만 ID와 이름은 고유하지 않습니다.

예: <input type="checkbox" id="c2" name="c2" value="DE039230952"/>

값이 설정된 확인란 만 선택하려면 어떻게합니까?


다음 querySelectorAll()과 같이 사용할 수 있습니다 .

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

이것은 다음으로 번역됩니다.

"value"속성이있는 모든 입력을 가져오고 공백이 아닌 "value"속성을가집니다.

이 데모에서는 값이 비어 있지 않은 확인란을 비활성화합니다.


추가 팁 :

다중 "nots", 숨겨지지 않고 비활성화되지 않은 입력 :

:not([type="hidden"]):not([disabled])

또한 이것을 할 수 있다는 것을 알고 계셨습니까?

node.parentNode.querySelectorAll('div');

이것은 jQuery와 동일합니다.

$(node).parent().find('div');

"노드"와 그 아래의 모든 div를 재귀 적으로 효과적으로 찾을 수 있습니다. HOT DAMN!


귀하의 예 :

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

예제에서 $$를 document.querySelectorAll로 바꿉니다.

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

다음과 함께 예제를 직접 사용하십시오.

const $$ = document.querySelectorAll.bind(document);

몇 가지 추가 사항 :

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

참고 URL : https://stackoverflow.com/questions/10777684/how-to-use-queryselectorall-only-for-elements-that-have-a-specific-attribute-set

반응형