Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  108] [ 6]  / answers: 1 / hits: 25996  / 11 Years ago, thu, august 15, 2013, 12:00:00

I was wondering about two different syntax of selecting element in JavaScript.


suppose if I want to select all divs from current document then:


var divs = document.getElementsByTagName("div");
console.log("There are "+divs.length+" Divs in Document !");

Will work fine. But there is also another way of doing so, like:


var divs = document.querySelectorAll("div");
console.log("There are "+divs.length+" Divs in Document !");

When both of them works in the same way. What's the difference between them ?



  • Which one is faster?

  • Why?

  • How both works?

  • Thanks in advance. I've seen the questions like this but they didn't satisfied the need.


    More From » javascript

     Answers
    1

    Selections


    getElementsByTagName only selects elements based on their tag name. querySelectorAll can use any selector which gives it much more flexibility and power.


    Return value



    • gEBTN returns a live node list.

    • qSA returns a static node list.


    Live node lists can be useful (you can query once, store the value, and have it update as the DOM changes) but are responsible for a lot of confusion such as the example in this question.


    Usually a static list is easier to deal with.


    Support


    See caniuse for gEBTN and qSA.


    gEBTN has more support, but qSA has support in all browsers that are relevant for most use cases today.


    Performance


    You probably shouldn't care. These functions are unlikely to be a bottleneck in your code.


    I've seen conflicting reports about which is faster. It likely varies between browsers anyway.


    [#76350] Tuesday, August 13, 2013, 11 Years  [reply] [flag answer]
    Only authorized users can answer the question. Please sign in first, or register a free account.
    wilson

    Total Points: 27
    Total Questions: 93
    Total Answers: 93

    Location: Tajikistan
    Member since Sun, Aug 29, 2021
    3 Years ago
    wilson questions
    Tue, Aug 9, 22, 00:00, 2 Years ago
    Wed, May 11, 22, 00:00, 2 Years ago
    Wed, May 20, 20, 00:00, 4 Years ago
    Wed, May 13, 20, 00:00, 4 Years ago
    ;