+ 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()

16th Apr 2018, 8:22 AM
dCook
dCook - avatar
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.
16th Apr 2018, 3:25 PM
Mike Choy
Mike Choy - avatar
17th Apr 2018, 12:31 PM
Morpheus
Morpheus - avatar
+ 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.
16th Apr 2018, 10:45 AM
John Wells
John Wells - avatar
+ 3
woahhh!!
17th Apr 2018, 6:35 AM
Mirul Makenkov II
Mirul Makenkov II - avatar
+ 3
Morpheus Mike Choy I guess I have a bunch of code to change because I had no clue those collections were live and retrived them repeatedly each time I used them. Thanks for the information!
17th Apr 2018, 12:48 PM
John Wells
John Wells - avatar
+ 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
16th Apr 2018, 11:06 AM
Morpheus
Morpheus - avatar
+ 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>
17th Apr 2018, 12:16 PM
dCook
dCook - avatar
+ 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'))
17th Apr 2018, 12:20 PM
dCook
dCook - avatar
+ 1
@Mike I found out how this works. If anyone wants to see: https://jsfiddle.net/dcookdesign/h28ab89a/21/
17th Apr 2018, 1:56 PM
dCook
dCook - avatar