Order of elements in document.getElementsByClassName() array

后端 未结 1 933
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 05:07

I\'m calling

document.getElementsByClassName(\'fastSearch\', \'document.forms\'); 

in my js code on html.

Will I get the same orde

相关标签:
1条回答
  • 2021-01-18 05:27

    Yes, you will, on conforming implementations, but what it returns is not an array, it's an HTMLCollection. The results will be in document order (top-down, depth-first traversal — which is a fancy way of saying, what it looks like when you look at the markup :-) ).

    For example, with this document:

    <div id="d1" class="a">
        <div id="d2" class="a">
            <div id="d3" class="a"></div>
        </div>
        <div id="d4" class="a"></div>
    </div>
    <div id="d5" class="a"></div>
    

    getElementsByClassName("a") will reliably list them in order: d1, d2, d3, d4, d5.

    Note that getElementsByClassName is not supported by some older browsers, notably IE8. Everything vaguely-modern that supports it also supports the more generally-useful querySelectorAll (which supports a query based on any CSS selector), which (perversely) is in IE8 as well.

    Other notes:

    • On a conforming implementation, getElementsByClassName returns a live HTMLCollection, which means that if you add, remove, or change elements, the collection you already have will be updated. That can be useful and powerful, or surprising, depending on what you're doing with it.
    • querySelectorAll returns a snapshot NodeList, e.g., not a live HTMLCollection.

    Example:

    var byClassName = document.getElementsByClassName("a");
    var bySelector = document.querySelectorAll(".a");
    console.log("Before adding another one:");
    console.log("byClassName.length = " + byClassName.length);
    console.log("bySelector.length = " + bySelector.length);
    var div = document.createElement("div");
    div.className = "a"
    document.body.appendChild(div);
    console.log("AFTER adding another one:");
    console.log("byClassName.length = " + byClassName.length);
    console.log("bySelector.length = " + bySelector.length);
    <div id="d1" class="a">
      <div id="d2" class="a">
        <div id="d3" class="a"></div>
      </div>
      <div id="d4" class="a"></div>
    </div>
    <div id="d5" class="a"></div>

    0 讨论(0)
提交回复
热议问题