2013-01-17 3 views
89

querySelectorquerySelectorAll의 차이점은 getElementsByClassNamegetElementById인데 정확히 알고 싶습니다. this link에서querySelector 및 querySelectorAll vs JavaScript의 getElementsByClassName 및 getElementById

나는 querySelector와 내가 ID myid와 요소를 얻을 클래스 myclassdocument.querySelector("#myid")을 가진 요소를 얻을 수 document.querySelector(".myclass")을 쓸 수 있다는 것을 수집 할 수있다. 하지만 이미 getElementsByClassNamegetElementById을 할 수 있습니다. 어느 것이 더 선호되어야 하는가?

또한에서 작업하며 ID는 콜론으로 동적으로 생성되며 view:_id1:inputText1처럼 보입니다. 그래서 document.querySelector("#view:_id1:inputText1")이라고 쓰면 작동하지 않습니다. 그러나 document.getElementById("view:_id1:inputText1")을 쓰면 작동합니다. 어떤 아이디어?

+0

querySelector이 HTML 요소 ...이 ... 도장을 달성하기 위해 정규 표현식을 사용하여 쿼리에 대한 핵심 요소로서의 특성을 포함 할 수있는 HTML DOM 트리를 쿼리에 사용되는 다음과 같이 내 테스트 결과는. query()가 똑같은 일을한다 – anix

+0

'document.querySelectorAll (". myclass")'를 의미하지 않습니까? 'document.querySelector (". myclass")'를 사용하면 일치하는 첫 번째 요소 만 반환됩니다. – mhatch

답변

65

getElementsByClassName 및 getElementById에 대한 querySelector와 querySelectorAll의 차이점을 정확히 알고 싶습니다.

구문과 브라우저가 지원됩니다.

querySelector은 더 복잡한 선택기를 사용하려는 경우에 더 유용합니다.

.foo li

document.querySelector ("#보기 : _id1 : inputText1")가 작동하지 않습니다 foo는 클래스의 구성원 인 요소의 후손 모든 목록 항목. 그러나 document.getElementById ("view : _id1 : inputText1")를 작성하는 것이 효과적입니다. 어떤 아이디어?

: 문자는 선택자 안에 특별한 의미가 있습니다. 당신은 그것을 벗어나야합니다. (선택기 이스케이프 문자는 JS 문자열에서도 특별한 의미를 가지므로 도 이스케이프 처리해야합니다.

document.querySelector("#view\\:_id1\\:inputText1") 
+4

실적에 대한 아이디어가 있습니까? – Naveen

+1

브라우저마다 다르며 버전에 따라 다릅니다. 나는 셀렉터 기반의 것들이 더 비싸다고 생각할 것이다. (그러나 의미있는 방법이 될 수는 없다.) – Quentin

+2

@Naveen : JSPerf에 대한 결론을 추가 할 수 있습니까? 예를 들어 사이트가 오늘 다운되었으므로 수업에 대한 실적이 어떻게 비교되는지 궁금합니다. 감사! – jtheletter

5

querySelectorquerySelectorAllgetElementByIdgetElementsByClassName 반면에 많은 이상 우리와 함께 한 비교적 새로운 API입니다. 즉, 사용하는 브라우저는 대부분 어떤 브라우저를 지원해야하는지에 따라 달라집니다.

:은 특별한 의미가 있으므로 ID/클래스 이름의 일부로 사용해야하는 경우 이스케이프 처리해야합니다.

+1

성과에 대한 아이디어가 있습니까? – Naveen

+10

이것은 반드시 사실 일 필요는 없습니다. 예를 들어,'getElementsByClassName'은 그렇지 않지만'querySelectorAll'은 IE8에서 사용 가능합니다. – DaveJ

+0

'querySelectorAll' ... 기본적으로 모든 것 : http://caniuse.com/#search=querySelectorAll – dsdsdsdsd

15

querySelector (3) -Selector 함께이 같은 ID와 클래스와 의사 클래스와 완벽한 CSS 될 수 있습니다 getElementByClassName

'#id.class:pseudo' 

// or 

'tag #id .class .class.class' 

그냥 클래스를 정의 할 수 있습니다

'class' 

getElementById ID를 정의 할 수 있습니다.

'id' 
+1

': first'는 CSS 선택 자입니까? ': first-class' 또는': first-of-type' 일 수도 있지만,': first '는 JavaScript/jQuery/Sizzle 추가라고 생각했습니다. –

+0

방금 ​​전 당신에게 보여주고 싶었던,': pseudo-syntax'이 가능합니다. – algorhythm

+0

@DavidThomas 예, CSS3의 일부입니다. 다음과 같이 사용할 수 있습니다 : http://css-tricks.com/almanac/selectors/f/first-child/ – algorhythm

50

querySelector

제 매칭 소자를 반환 Mozilla Documentation:

에서 NodeSelector 인터페이스 이 사양은, DocumentFragment가, 또는 요소 인터페이스 문서 구현 물체에 두 개의 새로운 메서드가 추가 수집210 노드 하위 트리 내의 노드. 일치하는 노드가 없으면 null이 리턴됩니다. 더 일치가 발견되지 않으면 querySelectorAll

는 노드의 서브 트리 내에서 일치하는 모든 요소 노드를 포함하는 NodeList를, 또는 빈 NodeList를 돌려줍니다.

참고 : 살입니다 querySelectorAll()에 의해 반환 된 노드 목록. 라이브 노드 목록을 반환하는 다른 DOM 쿼리 메서드와 다른 입니다.

+11

+1 라이브 노드 목록 구분을 지적합니다.결과를 어떻게 사용할 것인지에 따라 매우 중요한 차이가 있습니다. – jmbpiano

+4

"살아 있지 않다"는 뜻 ... 감사합니다 ... – dsdsdsdsd

+2

"live"는 DOM 런타임에 추가 된 노드를 의미하며 그 newley 노드에 추가 작업을 할 수 있습니다 – diEcho

33

차이점에 대해서는 querySelectorAllgetElementsByClassName 사이의 결과에 중요한 값이 있습니다. 반환 값이 다릅니다. 은 정적 컬렉션을 반환하고 getElementsByClassName은 라이브 컬렉션을 반환합니다.

  • querySelectorAll로 생성 된 변수는 방법은를 호출 된 순간에 선택 을 충족 요소를 포함합니다 : 당신이 나중에 사용하기 위해 변수에 결과를 저장하는 경우이 혼란으로 이어질 수 있습니다.
  • getElementsByClassName으로 생성 된 변수에는 (메서드 호출시와 다를 수 있음)이 사용될 때 셀렉터를 충족하는 요소가 포함됩니다.
  • 예를 들어

, 클래스를 업데이트 한 후이 변수 aux1aux2를 재 할당하지 않은 경우에도, 서로 다른 값을 포함하는 방법주의 사항 :

// 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>

+2

그냥 언급하자면 - 이전의 모든 DOM API는 노드 목록 즉, document.getElementsByName ','document.getElementsByTagNameNS' 또는'document.getElementsByTagName'는 같은 행동을 보일 것입니다. – RBT

+1

일부 분석 결과에 따르면 querySelector는 getElementById보다 시간이 오래 걸립니다 (https://www.dimlucas.com/index.php/2016/09/17/jquery-vs-getelementbyid-vs-queryselector/ 등). 액세스 시간을 고려하면 어떨까요? getElementById에서 얻은 라이브 노드가 querySelector의 정적 노드보다 더 많은 시간이 걸립니까? – Eric

6

내가이 온 페이지를 순전히 성능의 측면에서 사용하는 더 나은 방법을 찾으려면 - 즉 빠르게 :

,693,210

나는이 발견 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