getElementByTagName vs querySelectorAll

Let me come straight to the point. I need to get all the div inside a html element. I have two options, I can use getElementByTagName or querySelectorAll. I know one thing for sure is that, querySelectorAll can be used for complex selector. But what I am going to show you in below code is a big difference in these two methods.

So, what I am doing up, my html is having two div nodes already, and I am using the both the method querySelectorAll(‘div’) and getElementsByTagName(‘div’) to get the nodes. Then I am adding a div dynamically.

Lets print the length of nodes I am getting by both the methods.

Wow, the length of getElementsByTagNameNodes increases just by adding a dynamic element. Reason for this behavior is querySelectorAll returns static NodeList, where as getElementsByTagName returns the live NodeList. Getting the live Node list is faster for browser, I don’t know the reason yet. Let’s find out. Please add your comments.

!Happy Coding

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *