Order of elements in document.getElementsByClassName() array

后端 未结 1 936
隐瞒了意图╮
隐瞒了意图╮ 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:

    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);

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