Copy Code code as follows:
function getElementsByTagName (node, tagName) {
var elements = [], i = 0, Anytag = TagName = = "*", next = Node.firstchild;
while (node = next) {
if (anytag? node.nodetype = = = 1:node.nodename = = tagName) elements[i++] = node;
Next = Node.firstchild | | node.nextsibling;
while (!next && node = node.parentnode)) next = node.nextsibling;
}
return elements;
};
Definitions and usage
The getElementsByTagName () method returns a collection of objects with the specified label name.
Grammar
document.getElementsByTagName (tagname)
Description
The order in which the getElementsByTagName () method returns elements is the order in which they are in the document.
If you pass the special string "*" to the getElementsByTagName () method, it returns a list of all the elements in the document, and the order in which they are arranged is the order in which they are in the document.
Tips and comments
Note: Strings passed to the getElementsByTagName () method can be case-insensitive.
Instance
Example 1
Copy Code code as follows:
<script type= "Text/javascript" >
function getelements ()
{
var x=document.getelementsbytagname ("input");
alert (x.length);
}
</script>
<body>
<input name= "Myinput" type= "text" size= "a"/><br/>
<input name= "Myinput" type= "text" size= "a"/><br/>
<input name= "Myinput" type= "text" size= "a"/><br/>
<br/>
<input type= "button" onclick= "GetElements ()"
Value= "How many input elements?"/>
</body>
Example 2
You can use the getElementsByTagName () method to get a list of HTML elements of any type. For example, the following code can get all the tables in the document:
Copy Code code as follows:
var tables = document.getelementsbytagname ("table");
Alert ("This document contains" + Tables.length + "tables");
Example 3
If you know a lot about the structure of a document, you can also use the getElementsByTagName () method to get a specific element in the document. For example, the following code can get a fourth paragraph in a document:
var Myparagragh = document.getElementsByTagName ("P") [3];
However, we still think that if you need to manipulate a particular element, it is more efficient to use the getElementById () method.