Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of the elements returned using getElementsByTagName ()

Tags:

javascript

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";
    }
}
like image 376
Anil Namde Avatar asked Feb 10 '11 06:02

Anil Namde


People also ask

What does getElementsByTagName return?

getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically.

What is the syntax of getElementsByTagName ()?

Syntax: var elements = document. getElementsByTagName(name);

What is the use of getElementsByTagName in Javascript?

The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection.

Does getElementsByTagName return an array?

getElementsByTagName - the method name itself implies that it will return multiple elements - i.e. an array. The method always returns an array, with the length equal to the number of matching elements. As such you must always access the elements by the index of the element in the array.


1 Answers

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

like image 52
kirilloid Avatar answered Jan 01 '23 07:01

kirilloid