Pages

Working with getElementsByTagName

In order to work on multiple elements with same tag name  we use property  getElementsByTagName . e.g.


                               var listElements = document.getElementsByTagName("ul");

This stores all the elements with the tag name ul (unordered list) in the variable listElements . All elements inside listElements form a nodelist . listElements behaves like an array . So , to retrieve third elements in the variable listElements we use statement :

                                   var Thirdtem = listElements[2];

The third element in listElements is now stored in the variable ThirdItem .


To know the number of elements in the listElements we use statement :

                                     var totalItems = listElements.length;

Suppose you have two ordered lists and four unordered list elements  with two unordered list elements nested inside each ordered list and you want to retrieve  only the unordered elements inside  second ordered list . There is a way to get around this as :


                        var orderedlists = document.getElementsByTagName("ol");
                        var secondList = orderedlists[1];
                        var secondListElements = secondList.getElementsByTagName("ul");


We can use this approach to access any element in the document .