QuerySelector series
andGetElementsBy 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.
querySelector
All of them are returnedNodeList
Object (that is, a collection of document nodes)GetElementsBy series
Returns 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
getElement
Returns the dynamic collection, yesdocument
The method; Good performance, generally preferentially used; The parameters received can only be simpleclassName
,tagName
andname
;querySelector
Returns a static collection, yeselement
The method ofcss Selector
theAPI
, the received parameter is oneCSS
Selector;getElement
thanquerySelector
The performance is good, generally for the selector is more complex (multi-layer nesting) and then consider usingquerySelector
;