programing tip

JavaScript의 querySelector 및 querySelectorAll vs getElementsByClassName 및 getElementById

itbloger 2020. 6. 16. 20:38
반응형

JavaScript의 querySelector 및 querySelectorAll vs getElementsByClassName 및 getElementById


나는 정확히의 차이점이 무엇인지 알고 싶습니다 querySelectorquerySelectorAll대한 getElementsByClassName그리고 getElementById?

에서 이 링크 내가 가진 것을 수집 할 수 querySelector내가 쓸 수있는 document.querySelector(".myclass")클래스 요소를 얻을 myclass하고 document.querySelector("#myid")ID와 요소를 얻을 myid. 하지만 난 이미 할 수있는 getElementsByClassName과를 getElementById. 어느 것을 선호해야합니까?

또한 ID가 콜론으로 동적으로 생성되고 다음과 같이 보이는 XPage 에서 작업 합니다 view:_id1:inputText1. 그래서 내가 쓸 때 document.querySelector("#view:_id1:inputText1")작동하지 않습니다. 그러나 작문 document.getElementById("view:_id1:inputText1")은 효과가 있습니다. 어떤 아이디어가 있습니까?


getElementsByClassName과 getElementById에 대해 querySelector와 querySelectorAll의 차이점이 정확히 무엇인지 알고 싶습니다.

구문 및 브라우저 지원

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

예를 들어 foo 클래스의 멤버 인 요소의 모든 목록 항목 .foo li

document.querySelector ( "# view : _id1 : inputText1") 작동하지 않습니다. 그러나 document.getElementById ( "view : _id1 : inputText1") 작성이 작동합니다. 어떤 아이디어가 있습니까?

:문자 선택기 내부에 특별한 의미가 있습니다. 당신은 그것을 탈출해야합니다. 선택기 이스케이프 문자는 JS 문자열에서도 특별한 의미를 가지므로 이스케이프 문자도 이스케이프 해야 합니다.

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

Mozilla 문서 에서 수집 :

NodeSelector 인터페이스이 사양은 Document, DocumentFragment 또는 Element 인터페이스를 구현하는 모든 객체에 두 가지 새로운 메소드를 추가합니다.

querySelector

노드의 서브 트리 내 에서 첫 번째로 일치하는 Element 노드를 리턴합니다 . 일치하는 노드가 없으면 null이 반환됩니다.

querySelectorAll

노드의 서브 트리 내에서 일치하는 모든 Element 노드를 포함 하는 NodeList를 리턴 하거나 일치하는 것이 없으면 빈 NodeList를 리턴합니다 .

참고 :에 의해 반환 된 NodeList querySelectorAll()는 활성 상태가 아니므로 DOM의 변경 사항이 컬렉션에 반영되지 않습니다. 이것은 라이브 노드 목록을 반환하는 다른 DOM 쿼리 방법과 다릅니다.


차이점에 대해, 사이의 결과에 중요한 하나가 querySelectorAllgetElementsByClassName: 반환 값이 다릅니다. querySelectorAll정적 컬렉션을 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>


이 답변, 난을 참조 querySelector하고 querySelectorAll*과에 querySelector로 getElementById, getElementsByClassName, getElementsByTagName, 및 getElementsByNamegetElement로 *.

주요 차이점

  1. querySelector *는 id, tag 또는 class에 대한 단순한 선택기뿐만 아니라 모든 CSS3 선택기에 전달할 수 있으므로 더 유연합니다.
  2. querySelector *의 성능은 호출 된 DOM의 크기에 따라 변경됩니다. 정확하게 말하면 querySelector * 호출은 O (n) 시간에 실행되고 getElement * 호출은 O (1) 시간에 실행됩니다. 여기서 n은 호출 된 요소 또는 문서의 모든 하위의 총 수입니다. 이 사실은 가장 잘 알려지지 않은 것 같습니다. 대담합니다.
  3. getElement* calls return direct references to the DOM, whereas querySelector* internally makes copies of the selected elements before returning references to them. These are referred to as "live" and "static" elements. This is NOT strictly related to the types that they return. There is no way I know of to tell if an element is live or static programmatically, as it depends on whether the element was copied at some point, and is not an intrinsic property of the data. Changes to live elements apply immediately - changing a live element changes it directly in the DOM, and therefore the very next line of JS can see that change, and it propagates to any other live elements referencing that element immediately. Changes to static elements are only written back to the DOM after the current script is done executing. These extra copy and write steps have some small, and generally negligible, effect on performance.
  4. The return types of these calls vary. querySelector and getElementById both return a single element. querySelectorAll and getElementsByName both return NodeLists, being newer functions that were added after HTMLCollection went out of fashion. The older getElementsByClassName and getElementsByTagName both return HTMLCollections. Again, this is essentially irrelevant to whether the elements are live or static.

These concepts are summarized in the following table.

Function               | Live? | Type           | Time Complexity
querySelector          |   N   | Element        |  O(n)
querySelectorAll       |   N   | NodeList       |  O(n)
getElementById         |   Y   | Element        |  O(1)
getElementsByClassName |   Y   | HTMLCollection |  O(1)
getElementsByTagName   |   Y   | HTMLCollection |  O(1)
getElementsByName      |   Y   | NodeList       |  O(1)

Details, Tips, and Examples

  • HTMLCollections are not as array-like as NodeLists and do not support .forEach(). I find the spread operator useful to work around this:

    [...document.getElementsByClassName("someClass")].forEach()

  • Every element, and the global document, have access to all of these functions except for getElementsByName, which is only implemented on document.

  • Chaining getElement* calls instead of using querySelector* will improve performance, especially on very large DOMs. Even on small DOMs and/or with very long chains, it is generally faster. However, unless you know you need the performance, the readability of querySelector* should be preferred. querySelectorAll is often harder to rewrite, because you must select elements from the NodeList or HTMLCollection at every step. For example, the following code does not work:

    document.getElementsByClassName("someClass").getElementsByTagName("div")

    because you can only use getElements* on single elements, not collections. For example:

    document.querySelector("#someId .someClass div")

    could be written as:

    document.getElementById("someId").getElementsByClassName("someClass")[0].getElementsByTagName("div")[0]

    Note the use of [0] to get just the first element of the collection at each step that returns a collection, resulting in one element at the end just like with querySelector.

  • Since all elements have access to both querySelector* and getElement* calls, you can make chains using both calls, which can be useful if you want some performance gain, but cannot avoid a querySelector that can not be written in terms of the getElement* calls.

  • Though it is generally easy to tell if a selector can be written using only getElement* calls, there is one case that may not be obvious:

    document.querySelectorAll(".class1.class2")

    can be rewritten as

    document.getElementsByClassName("class1 class2")

  • Using getElement* on a static element fetched with querySelector* will result in an element that is live with respect to the static subset of the DOM copied by querySelector, but not live with respect to the full document DOM... this is where the simple live/static interpretation of elements begins to fall apart. You should probably avoid situations where you have to worry about this, but if you do, remember that querySelector* calls copy elements they find before returning references to them, but getElement* calls fetch direct references without copying.

  • Neither API specifies which element should be selected first if there are multiple matches.

  • Because querySelector iterates through the DOM until it finds a match (see Main Difference #2), the above also implies that you cannot rely on the position of an element you are looking for in the DOM to guarantee that it is found quickly - the browser may iterate through the DOM backwards, forwards, depth first, breadth first, or otherwise.


I came to this page purely to find out the better method to use in terms of performance - i.e. which is faster:

querySelector / querySelectorAll or getElementsByClassName

and I found this: https://jsperf.com/getelementsbyclassname-vs-queryselectorall/18

It runs a test on the 2 x examples above, plus it chucks in a test for jQuery's equivalent selector as well. my test results were as follows:

getElementsByClassName = 1,138,018 operations / sec - <<< clear winner
querySelectorAll = 39,033 operations / sec
jquery select = 381,648 operations / sec

querySelector can be a complete CSS(3)-Selector with IDs and Classes and Pseudo-Classes together like this:

'#id.class:pseudo'

// or

'tag #id .class .class.class'

with getElementByClassName you can just define a class

'class'

with getElementById you can just define an id

'id'

querySelector and querySelectorAll are a relatively new APIs, whereas getElementById and getElementsByClassName have been with us for a lot longer. That means that what you use will mostly depend on which browsers you need to support.

As for the :, it has a special meaning so you have to escape it if you have to use it as a part of a ID/class name.


Difference between "querySelector" and "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>


querySelector is of w3c Selector API

getElementBy is of w3c DOM API

IMO the most notable difference is that the return type of querySelectorAll is a static node list and for getElementsBy it's a live node list. Therefore the looping in demo 2 never ends because lis is live and updates itself during each iteration.

// 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")); 
}

look at this

https://codepen.io/bagdaulet/pen/bzdKjL

getElementById fastest than querySelector on 25%

jquery is slowest

var q = time_my_script(function() {

    for (i = 0; i < 1000000; i++) {
         var w = document.querySelector('#ll');
    }

});

console.log('querySelector: '+q+'ms');

The main difference between querySelector and getlementbyID(Claassname,Tagname etc) is if there is more than one elements which satifies the condition querySelector will return only one output whereas getElementBy* will return all the elements.

Lets consider an example to make it more clear.

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

Below code will explain the difference

**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.

Inshort if we want to select single element go for queryslector or if we want multiple element go for getElement

참고URL : https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid

반응형