You can find the element you wish to operate on in several ways:
By using the getElementById() and getElementsByTagName() methods
By using the parentNode, firstChild and lastChild properties of an element node
##getElementById() and getElementsByTagName()
The two methods, getElementById() and getElementsByTagName(), can find any HTML element in the entire HTML document. These two methods ignore the structure of the document. If you wish to find allelements in the document, getElementsByTagName() will find them all, regardless of where the
element is located in the document. Also, the getElementById() method returns the correct element, no matter where it is hidden in the document structure.
These two methods will provide you with any HTML elements you need, no matter where they are in the document! getElementById() can return elements by the specified ID:getElementById() Syntax
document.getElementById("ID");
getElementsByTagName() Syntax
document.getElementsByTagName("标签名称");
document.getElementById('ID').getElementsByTagName("标签名称");
Example 1
The following example will return allin the document A node list of elements:
document.getElementsByTagName("p");
Example 2
The following example will return a node of allelements list, and these
elements must be descendants of the element with id "mainp":
document.getElementById('mainp').getElementsByTagName("p");
NodeList (nodeList)
When we use a node list, we usually save the list in a variable, like this:var x=document.getElementsByTagName("p");
elements in the page, and we can access these
elements by their index numbers.
Note: Index numbers start from 0.
You can loop through the node list by using the length attribute:var x=document.getElementsByTagName("p"); for (var i=0;i Copy after login
element, you would write:
var y=x[2];
parentNode, firstChild and lastChild
These three attributes parentNode, firstChild and lastChild can follow the structure of the document and perform "short distance travel" in the document. Please look at the following HTML fragment:<table> <tr> <td>John</td> <td>Doe</td> <td>Alaska</td> </tr> </table>
The above is the detailed content of Detailed explanation of method examples for javascript to find and access dom nodes. For more information, please follow other related articles on the PHP Chinese website!