Javascript DOM provides a getElementsByTagName method that can be accessed using the documentElement property of document object. getElementsByTagName method returns the node list array of HTML document elements present in the HTML web page. You can pass the name of the particular HTML tag such as div, span, p etc whose list of array you want to collect. documentElement property of document object returns the root HTML element of the HTML document. Later on, in Javascript tutorials we will discuss about the getElementsByTagName method to access the nodes of XML documents also.
Syntax for Javascript document getElementsByTagName
var nodeList = document.documentElement.getElementsByTagName( "TAG NAME" );
Above syntax can be used to get the list of all the similar HTML elements e.g.: HTML <div> tag, HTML <span> tag.
E.g.:
var nodeList = document.documentElement.getElementsByTagName( "div" );
Above example code for getElementsByTagName will return the collection of all the div elements in the HTML document.
Properties and Functions of getElementsByTagName
You can access the following functions and properties of getElementsByTagName method:
item
item function accepts a parameter as index of the item you want to get from the array of specified HTML elements.
document.documentElement.getElementsByTagName( "div" ).item(0)
above code will return the first div element of the HTML document.
namedItem
namedItem function of getElementsByTagName method also accepts one parameter as value of id attribute of the specified HTML Tag and returns the Javascript object of that element.
document.documentElement.getElementsByTagName( "div" ).namedItem( "div1" )
you can further access the properties and methods for that HTML element object:
document.documentElement.getElementsByTagName( "div" ).namedItem( "div1" ).style.color
length
length property returns the number of specified HTML Tags found in the document.
document.documentElement.getElementsByTagName( "div" ).length
You can pass * at the place of HTML tag name to get the collection of all the available HTML elements present in the HTML document.
Continue to next tutorial: Javascript getElementsByTagName Loop to learn how to access the properties of HTML objects returned by the getElementsByTagName collection using JavaScript loop over the items.