简体   繁体   中英

Order of the elements returned using getElementsByTagName ()

Reading the controls using getElementsByTagName is very common practice to read the element. However I would like to know that whether we can trust the order in which the elements are returned using this function.

Does it return elements in the order in which they are placed on the UI? Or it can return random elements too where we can't trust on the sequence at other times?

var labels = document.getElementsByTagName("label"), i;
for(i=0;i<labels.length;i++)
{
    if(i == 1)
        labels[i].innerText = "First Value";
    else if (i==2)
        labels[i].innerText = "Second Value";

    if (labels[i].innerText  == "NULL") {
        labels[i].innerText  = "Empty";
    }
}

This function always return elements in the same depth-first order.
This is the order, in which they appear in HTML tree structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM