最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Order of the elements returned using getElementsByTagName () - Stack Overflow

programmeradmin3浏览0评论

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";
    }
}

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";
    }
}
Share Improve this question edited Oct 10, 2016 at 12:00 BuZZ-dEE 6,92916 gold badges73 silver badges105 bronze badges asked Feb 10, 2011 at 6:21 Anil NamdeAnil Namde 6,60811 gold badges65 silver badges101 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 20

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

发布评论

评论列表(0)

  1. 暂无评论