QuerySelector seriesandGetElementsBy series

GetElementsById (getElementsById); getElementsById (getElementsById); getElementsById (getElementsById); getElementsById (getElementsById)

QuerySelector belongs to the Selectors API specification in the W3C, and receives a CSS selector as an argument. The getElementsBy series is part of the W3C DOM specification.

  • querySelectorAll of them are returnedNodeListObject (that is, a collection of document nodes)
  • GetElementsBy seriesReturns theHTMLCollection(Collection of HTML elements)
  • Note that both return a set, and if you want to use the elements, you need to fetch them by index;

The difference between

GetElement gets a dynamic collection, while querySelector gets a static collection; What’s the difference between these two features? Dynamically selected elements change as the document changes, while static elements do not. Let’s take an unordered list as an example:

<ul>
    <li>Lisa</li>
    <li>Jennie</li>
    <li>Rose</li>
    <li>Jisoo</li>
</ul>
Copy the code

Next, get the DOM element

const ul1 = document.getElementsByTagName('ul');
const ul2 = document.querySelectorAll('ul')
ul1[0].appendChild(document.createElement('li'));
ul2[0].appendChild(document.createElement('li'));
console.log(li1.length);  / / 6
console.log(li2.length);  / / 4
Copy the code

Run the code above, you can see, whether to add a node can be ul1 or ul2 success be rendered to the page, but when we print out ul1 and ul2 can discover, through getElement access to the collection of elements changed (length value added 2), The length of the querySelector element is constant;

That is, if you want to dynamically retrieve a newly created DOM element, you can do so only through getElementsByClassName.

The performance comparison

This is determined by comparing the running time of the two elements

console.time('querySelectorAll');
for (let i = 0; i < 1000; i++) {
    document.querySelectorAll('li');
}
console.timeEnd('querySelectorAll');
console.time('getElementsByTagName');
for (let i = 0; i < 1000; i++) {
    document.getElementsByTagName('li');
}
console.timeEnd('getElementsByTagName');
Copy the code

The following output is displayed:

As you can see, the getElement method is several times faster than the querySelector method; In other words, the performance of getElement is indeed better

conclusion

  • getElementReturns the dynamic collection, yesdocumentThe method; Good performance, generally preferentially used; The parameters received can only be simpleclassName,tagNameandname;
  • querySelectorReturns a static collection, yeselementThe method ofcss SelectortheAPI, the received parameter is oneCSSSelector;
  • getElementthanquerySelectorThe performance is good, generally for the selector is more complex (multi-layer nesting) and then consider usingquerySelector;