+ 1
Get... vs. Query...
What is better to use (or more efficient) and why? (Supposing you want just one element returned) document.getElementById() document.getElementsByClassName() Or document.querySelector()
9 Respostas
+ 4
The Key difference is that Query Selector returns a static node list vs a live one with by ID/s ie if the DOM changes the live list would update accordingly.
Performance is not really material for a single element.
+ 6
Mike Choy that static list Vs a live list reference was a revelation, I looked for more
https://stackoverflow.com/questions/28163033/when-is-nodelist-live-and-when-is-it-static
https://developer.mozilla.org/en-US/docs/Web/API/NodeList
+ 4
I don't know for sure, but assume the gets would be faster as the query would need to parse the string to figure out what to search for.
+ 3
woahhh!!
+ 1
document.querySelector and
document.querySelectorAll relies heavily on parsing so it must be slow,
I know that document.getElementById and
document.getElementsByTagName are pretty fast, but ll need to do some tests
+ 1
@Mike I perhaps don't understand this "live list" issue. I thought that using query would basically take a frozen snapshot (from the sounds of it). But I've tried the following and that doesn't seem to be the case. Perhaps there's a different example that shows the issue better.
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
<script>
let a = document.querySelectorAll('.test'); //returns a NodeList
let b = document.getElementsByClassName('test'); // returns an HTMLCollection
a[0].innerHTML = "changed";
b[1].innerHTML = "changed";
console.log(a); //changed, NodeList
console.log(b); //changed, HTMLCollection
</script>
+ 1
Thanks everyone for your answers. I also spent some time looking around online. It looks like there's some other issues with using `query` methods. There are compatibility issues. Also slower as mentioned. I have yet to understand the "live list" issue as @mike choy mentioned. I also struggle a little to see what kind of situation that is relevant.
Anyway, I've settled that I will use `get` methods most of the time.
If I need to find something very specific with css selectors then `query` methods will be very good. (i.e. document.querySelector('.chicken feet'))
+ 1
@Mike I found out how this works. If anyone wants to see:
https://jsfiddle.net/dcookdesign/h28ab89a/21/