query Selector 및 query SelectorJavaScript의 모든 vs getElementsByClassName 및 getElementById
정확히 어떤 차이가 있는지 알고 싶습니다.querySelector
그리고.querySelectorAll
그에 반대하여getElementsByClassName
그리고.getElementById
?
이 링크에서 나는 그것을 수집할 수 있었다.querySelector
나는 쓸 수 있다document.querySelector(".myclass")
품격 있는 요소를 얻다myclass
그리고.document.querySelector("#myid")
ID를 가진 요소를 얻다myid
하지만 난 이미 할 수 있어getElementsByClassName
그리고.getElementById
어떤 것이 더 좋습니까?
또한 XPage에서는 콜론으로 ID가 동적으로 생성되어 다음과 같이 보입니다.view:_id1:inputText1
그래서 글을 쓸 때document.querySelector("#view:_id1:inputText1")
동작되지 않습니다.하지만 글쓰기는document.getElementById("view:_id1:inputText1")
왜 그런지 알아?
이 답변에 대해서는querySelector
그리고.querySelectorAll
query Selector* 및 to로 지정합니다.getElementById
,getElementsByClassName
,getElementsByTagName
,그리고.getElementsByName
getElement*로 지정합니다.
이 정보는 사양에서 확인할 수 있는 것이 많으며, 그 대부분은 제가 작성했을 때 실행한 다양한 벤치마크에서 얻은 것입니다.사양: https://dom.spec.whatwg.org/
주요 차이점
- query Selector*는 id, 태그 또는 클래스의 단순한 셀렉터뿐만 아니라 임의의 CSS3 셀렉터를 전달할 수 있기 때문에 유연성이 높아집니다.
- query Selector*의 성능은 부팅되는 DOM 크기에 따라 달라집니다.정확히 말하면 querySelector* 콜은 O(n) 타임으로 실행되고 getElement* 콜은 O(1) 타임으로 실행됩니다.n은 요소 또는 문서가 호출된 모든 자식의 합계 수입니다.이 사실은 가장 잘 알려지지 않은 것 같아서 과감하게 말씀드립니다.
- 이러한 콜의 반환 타입은 다양합니다.
querySelector
그리고.getElementById
둘 다 단일 요소를 반환합니다.querySelectorAll
그리고.getElementsByName
둘 다 NodeLists를 반환합니다.나이 든 사람getElementsByClassName
그리고.getElementsByTagName
둘 다 HTMLCollection을 반환합니다.NodeLists와 HTMLCollection은 모두 요소의 집합이라고 불립니다. - 컬렉션에는 DOM의 요소에 대한 참조 또는 요소의 복사본이 포함될 수 있습니다.getElement* 호출은 참조 컬렉션을 반환하지만 querySelectorAll 결과에는 요소의 복사본이 포함됩니다.이것들은 각각 「라이브」컬렉션과 「스태틱」컬렉션이라고 불립니다.이는 반환되는 유형과 관련이 없습니다.
이러한 개념은 다음 표에 요약되어 있습니다.
Function | Live? | Type | Time Complexity
querySelector | | Element | O(n)
querySelectorAll | N | NodeList | O(n)
getElementById | | Element | O(1)
getElementsByClassName | Y | HTMLCollection | O(1)
getElementsByTagName | Y | HTMLCollection | O(1)
getElementsByName | Y | NodeList | O(1)
상세, 힌트 및 예시
HTML Collection은 Node Lists만큼 어레이와 유사하지 않으며 .forEach()를 지원하지 않습니다.확산 연산자는 이 문제를 해결하는 데 유용합니다.
[...document.getElementsByClassName("someClass")].forEach()
모든 요소 및 글로벌
document
는, 다음의 모든 기능에 액세스 할 수 있습니다.getElementById
그리고.getElementsByName
에만 실장되어 있습니다.document
.query Selector*를 사용하는 대신 getElement* 콜을 체인으로 하면 특히 매우 큰 DOM에서 퍼포먼스가 향상됩니다.소형 DOM이나 매우 긴 체인을 사용하는 경우에도 일반적으로는 고속입니다.단, 퍼포먼스가 필요한 경우를 제외하고 query Selector* 가독성이 우선됩니다.
querySelectorAll
스텝마다 NodeList 또는HTMLCollection에서 요소를 선택해야 하기 때문에 개서가 어려운 경우가 많습니다.예를 들어 다음 코드가 작동하지 않습니다.document.getElementsByClassName("someClass").getElementsByTagName("div")
getElements*는 컬렉션이 아닌 단일 요소에서만 사용할 수 있기 때문입니다.예를 들어 다음과 같습니다.
document.querySelector("#someId .someClass div")
다음과 같이 쓸 수 있습니다.
document.getElementById("someId").getElementsByClassName("someClass")[0].getElementsByTagName("div")[0]
의 사용에 주의해 주세요.
[0]
컬렉션을 반환하는 각 단계에서 컬렉션의 첫 번째 요소만 가져오면 다음과 같이 끝에 하나의 요소가 생성됩니다.querySelector
.모든 요소가 querySelector* 콜과 getElement* 콜 모두에 액세스할 수 있으므로 두 콜을 모두 사용하여 체인을 만들 수 있습니다.이것은 퍼포먼스를 향상시키고 싶지만 getElement* 콜로 쓸 수 없는 querySelector를 피할 수 없습니다.
일반적으로 셀렉터가 getElement* 콜만을 사용하여 쓸 수 있는지 여부를 쉽게 알 수 있지만 명확하지 않을 수 있는 경우가 있습니다.
document.querySelectorAll(".class1.class2")
라고 고쳐 쓸 수 있다
document.getElementsByClassName("class1 class2")
querySelector*를 사용하여 Import된 정적 요소에 getElement*를 사용하면 querySelector에 의해 복사된 DOM의 정적 서브셋에 대해서는 활성화되지만 완전한 문서 DOM에 대해서는 활성화되지 않습니다.여기서 요소에 대한 단순한 라이브/스터틱 해석이 무너지기 시작합니다.이 문제에 대해 걱정할 필요가 있는 상황은 피해야 합니다.단, 그럴 경우 참조를 반환하기 전에 querySelector* 호출이 검출된 복사 요소를 호출하지만 getElement* 호출은 복사하지 않고 직접 참조를 가져옵니다.
query Selector* 및
getElementById
사양에서 "트리 순서"라고 하는 사전 순서, 깊이 우선으로 요소를 통과시킵니다.다른 getElement* 콜의 경우 사양상 명확하지 않습니다.트리의 순서와 같은 경우가 있습니다만,getElementsByClassName(".someClass")[0]
는, 모든 브라우저로 같은 결과를 얻을 수 없는 경우가 있습니다.getElementById("#someId")
단, 페이지에 동일한 ID의 복사본이 여러 개 있는 경우에도 마찬가지입니다.
query Selector와 query Selector의 정확한 차이를 알고 싶습니다.getElementsByClassName 및 getElementById를 모두 부정합니까?
구문 및 브라우저 지원.
querySelector
는, 보다 복잡한 실렉터를 사용하는 경우에 편리합니다.
예: foo 클래스의 멤버인 요소에서 파생된 모든 목록 항목:.foo li
문서.query Selector("#view:_id1:inputText1")는 동작하지 않습니다.그러나 document.getElementById("view:_id1:inputText1")를 쓰면 됩니다.왜 그런지 알아요?
그:
character는 셀렉터 안에서 특별한 의미를 가집니다.탈출해야 합니다.(실렉터 이스케이프 문자는 JS 문자열에서도 특별한 의미가 있기 때문에 그 의미도 탈출해야 합니다.
document.querySelector("#view\\:_id1\\:inputText1")
NodeSelector 인터페이스 이 사양에서는 Document, DocumentFragment 또는 Element 인터페이스를 구현하는 오브젝트에 다음 두 가지 새로운 메서드가 추가됩니다.
query Selector(쿼리 셀렉터)
노드의 하위 트리 내에서 일치하는 첫 번째 요소 노드를 반환합니다.일치하는 노드가 발견되지 않으면 null이 반환됩니다.
query Selector(쿼리 셀렉터)모든.
노드의 하위 트리 내에 일치하는 모든 요소 노드가 포함된 NodeList를 반환하거나 일치하는 항목이 없는 경우 빈 NodeList를 반환합니다.
그리고.
" "에 의해 : " " NodeList"
querySelectorAll()
는 라이브가 아닙니다.즉, DOM 의 변경은 컬렉션에 반영되지 않습니다.이는 라이브 노드목록을 반환하는 다른 DOM 쿼리 방식과는 다릅니다.
, 그 .querySelectorAll
★★★★★★★★★★★★★★★★★」getElementsByClassName
반환값이 다릅니다. querySelectorAll
는 스태틱하고, 「」는 「」를 참조해 주세요.getElementsByClassName
이치노나중에 사용할 수 있도록 결과를 변수에 저장할 경우 혼란이 발생할 수 있습니다.
- 에서 생성된
querySelectorAll
에는 메서드가 호출된 시점에서 실렉터를 채운 요소가 포함됩니다. - 에서 생성된
getElementsByClassName
에는 셀렉터를 사용할 때 셀렉터를 채운 요소가 포함됩니다(메서드가 호출된 시점과는 다를 수 있습니다).
를 들어 않은 .aux1
★★★★★★★★★★★★★★★★★」aux2
후 이 달라집니다 , 래클갱 릅릅 릅릅 릅릅 릅릅 릅릅 릅릅 릅릅 릅 , , , 。
// storing all the elements with class "blue" using the two methods
var aux1 = document.querySelectorAll(".blue");
var aux2 = document.getElementsByClassName("blue");
// write the number of elements in each array (values match)
console.log("Number of elements with querySelectorAll = " + aux1.length);
console.log("Number of elements with getElementsByClassName = " + aux2.length);
// change one element's class to "blue"
document.getElementById("div1").className = "blue";
// write the number of elements in each array (values differ)
console.log("Number of elements with querySelectorAll = " + aux1.length);
console.log("Number of elements with getElementsByClassName = " + aux2.length);
.red { color:red; }
.green { color:green; }
.blue { color:blue; }
<div id="div0" class="blue">Blue</div>
<div id="div1" class="red">Red</div>
<div id="div2" class="green">Green</div>
이 페이지를 찾은 것은 퍼포먼스 측면에서 보다 나은 방법을 찾기 위해서입니다.즉, 어느 쪽이 더 빠른지,
querySelector / querySelectorAll or getElementsByClassName
https://jsperf.com/getelementsbyclassname-vs-queryselectorall/18을 찾았습니다.
위의 2개의 예에 대한 테스트를 실행하고 jQuery의 동등한 셀렉터에 대한 테스트에서도 척킹합니다. 제 테스트 결과는 다음과 같습니다.
getElementsByClassName = 1,138,018 operations / sec - <<< clear winner
querySelectorAll = 39,033 operations / sec
jquery select = 381,648 operations / sec
querySelector
와 클래스와 의사 가 될 수.
'#id.class:pseudo'
// or
'tag #id .class .class.class'
getElementsByClassName
요.
'class'
getElementById
아이디 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」
'id'
querySelector
★★★★★★★★★★★★★★★★★」querySelectorAll
는 비교적 "API"는getElementById
★★★★★★★★★★★★★★★★★」getElementsByClassName
어떤 지원하느냐에 을 의미합니다.
:
특별한 의미가 있기 때문에 아이디/클래스 이름의 일부로 사용해야 할 경우 이를 회피해야 합니다.
querySelector
w3c Selector API 입니다.
getElementBy
w3c DOM API 입니다.
할 만한 은 IMO의 입니다.querySelectorAll
로, 「」의 경우입니다.getElementsBy
실시간 노드 목록입니다.는 「2」로 종료되지 않습니다.은 「2」로 종료됩니다.lis
는 라이브이며 반복할 때마다 자동으로 갱신됩니다.
// Demo 1 correct
var ul = document.querySelectorAll('ul')[0],
lis = ul.querySelectorAll("li");
for(var i = 0; i < lis.length ; i++){
ul.appendChild(document.createElement("li"));
}
// Demo 2 wrong
var ul = document.getElementsByTagName('ul')[0],
lis = ul.getElementsByTagName("li");
for(var i = 0; i < lis.length ; i++){
ul.appendChild(document.createElement("li"));
}
"querySelector"와 "querySelectorAll"의 차이점
//querySelector returns single element
let listsingle = document.querySelector('li');
console.log(listsingle);
//querySelectorAll returns lit/array of elements
let list = document.querySelectorAll('li');
console.log(list);
//Note : output will be visible in Console
<ul>
<li class="test">ffff</li>
<li class="test">vvvv</li>
<li>dddd</li>
<li class="test">ddff</li>
</ul>
이것 좀 봐요.
https://codepen.io/bagdaulet/pen/bzdKjL
getElementById가 25%에서 querySelector보다 빠릅니다.
jquery가 가장 느리다.
var q = time_my_script(function() {
for (i = 0; i < 1000000; i++) {
var w = document.querySelector('#ll');
}
});
console.log('querySelector: '+q+'ms');
querySelector와 getlementby의 주요 차이점ID(Classname, Tagname 등)는 조건을 만족시키는 요소가 여러 개 있는 경우 selector는 출력을 하나만 반환하고 getElementBy*는 모든 요소를 반환합니다.
예를 들어 좀 더 명확히 하자.
<nav id="primary" class="menu">
<a class="link" href="#">For Business</a>
<a class="link" href="#">Become an Instructor</a>
<a class="link" href="#">Mobile Applications</a>
<a class="link" href="#">Support</a>
<a class="link" href="#">Help</a>
</nav>
아래 코드는 차이점을 설명합니다.
**QUERY SELECTOR**
document.querySelector('.link'); // Output : For Business (element)
document.querySelectorAll('.link'); //Out All the element with class link
**GET ELEMENT**
document.getElementsByClassName('link') // Output : will return all the element with a class "link" but whereas in query selector it will return only one element which encounters first.
단일 요소를 쿼리 셀렉터에 대해 선택하거나 다중 요소를 getElement에 대해 선택합니다.
언급URL : https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid
'itsource' 카테고리의 다른 글
JPA: 대규모 결과 세트에 대해 반복하기 위한 적절한 패턴은 무엇입니까? (0) | 2022.09.13 |
---|---|
문자열이 JS의 regex와 일치하는지 확인합니다. (0) | 2022.09.13 |
MySQL CREATE/DROP USER가 0을 반환함 (0) | 2022.09.13 |
요소를 어레이에 특정 위치에 삽입하려면 어떻게 해야 합니까? (0) | 2022.09.13 |
MySQL과 다른 MariaDB 프로토콜 문서를 찾을 수 있는 위치 (0) | 2022.09.13 |