HTML DOM getElementsByTagName() Method
Definition and Usage
getElementsByTagName() method can return a collection of objects with the specified tag name.
Syntax
document.getElementsByTagName(tagname)
Description
The order of elements returned by getElementsByTagName() method is the order in which they appear in the document.
If the special string "*" is passed to the getElementsByTagName() method, it will return a list of all elements in the document, and the order of the elements is the order in which they appear in the document.
Tips and comments
Note:The string passed to getElementsByTagName() method can be case-insensitive.
Instance
Example 1
<html>
<head>
<script type="text/javascript">
function getElements()
{
var x=document.getElementsByTagName("input")
;
alert(x.length);
}
</script>
</head>
<body>
<input name="myInput" type="text" size="20" /><br />
<input name="myInput" type="text" size="20" /><br />
<input name="myInput" type="text" size="20" /><br />
<br />
<input type="button" onclick="getElements()"
value="How many input elements?" />
</body>
</html>
Example 2
You can use the getElementsByTagName() method to get a list of any type of HTML elements. For example, the following code can get all the tables in the document:
var tables = document.getElementsByTagName("table")
;
alert("This document contains " + tables.length + " tables");
Example 3
If you are very familiar with the structure of the document, you can also use the getElementsByTagName() method to get a specific element from the document. For example, the following code can obtain the fourth paragraph in the document:
var myParagragh = document.getElementsByTagName("p")[3]
;
However, we still believe that if you need to operate a specific element, using the getElementById() method will be more effective.