getElementsByTagName (): The purpose of the method is to look for all elements that have a given signature.
element = document.getElementsByTagName (tagName);
This method returns a collection of nodes that can be treated as an array. The length property of this collection is equal to the total number of all elements in the current document that have a given signature. Each element in this array is an object, and they all have attributes such as NodeName, NodeType, ParentNode, ChildNodes, and so on.
The following example will search all the text segment elements (p elements) in the current document, and the length property of the node collection returned by the Getelementsbutagname () method will be saved to the variable Howmany:
var paras = document.getelementsbytagname ("P"); var howmany = paras.length;
After the successful return of the getElementsByTagName () method, the more common follow-up is to use a for loop to iterate through the elements of all the returned collections of this method, and in the For loop we can use SetAttribute (), Clone () or appendchild () and other methods to query the various relevant elements.
The following example iterates through all the text snippet elements in the current file and sets its Title property all to an empty string:
var paras = document.getelementsbytagname ("P"); for var i=0;i<paras.length;i++ ) { paras[i].setattribute ("title", ""); }
In the example above, the data type of the variable paras is nodelist. Each element in this collection can be accessed like any other array: Paras[0], paras[1], paras[2], and so on. Of course, you can also use the item () method: Paras.item[0] and so on.
The getElementsByTagName () method does not have to be used throughout the document, and he can also be used to find the element in the child of a particular element that the holder has given a signature.
In the following example, in the current document contains an id attribute value is a content element, in order to find out all the text fragment elements contained in the content element, we use the getElementsByTagName () method on the content:
var container = document.getElementById ("content"); var paras = container.getelementsbytagname ("P"); var howmany = paras.length;
After executing these statements, the value of the variable Howmany will be the total score of all the text elements contained in the content element, not the overall number of text segments contained within the document.
getElementsByTagName ()