The example in this article describes the JS method of accessing DOM nodes. Share it with everyone for your reference, as follows:
Find and access nodes
You can find the element you want to operate through several methods:
By using the getElementById() and getElementsByTagName() methods
By using an element The node's parentNode, firstChild and lastChild attributes
getElementById() and getElementsByTagName()
getElementById() and getElementsByTagName() are two methods that can find any HTML element in the entire HTML document.
These two methods ignore the structure of the document. If you wish to find all
elements 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() returns an element by a specified ID:
getElementById() Syntax
document.getElementById("ID");
Note: getElementById() does not work in XML. In an XML document, you must search by having an attribute of type id, which must be declared in the XML DTD. The
getElementsByTagName() method returns all elements (as a list of nodes) that are descendants of the element you are using when you use this method, using the specified tag name.
getElementsByTagName() can be used for any HTML element:
getElementsByTagName() Syntax
document.getElementsByTagName("标签名称");
or:
document.getElementById('ID').getElementsByTagName("标签名称");
Example 1
The following The example will return all< in the document A node list of p> elements:
document.getElementsByTagName("p");
Example 2
The following example will return a node list of all
elements, and these
elements must be with the id "maindiv" Descendants of elements:
document.getElementById('maindiv').getElementsByTagName("p");
Node List (nodeList)
When we use a node list, we usually save this list in a variable, like this:
var x=document.getElementsByTagName("p");
Now, the variable x contains a list of all
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
You can also access a specific element by its index number.
To access the third
element, you can write:
var y=x[2];
parentNode, firstChild and lastChild
These three properties parentNode, firstChild and lastChild can follow the structure of the document, in the document Take a "short trip".
Please look at the following HTML fragment:
<table> <tr> <td>John</td> <td>Doe</td> <td>Alaska</td> </tr> </table>
In the above HTML code, the first
In addition,