Javascript gets DOM node

There are many ways to obtain DOM nodes. You can obtain them based on the id attribute and tag name, or you can obtain child nodes, parent nodes, previous nodes, and next nodes.

This section explains how to obtain nodes based on the id attribute and label name of HTML tags.

getElementById() method

To obtain DOM nodes based on the id attribute of the HTML tag, please use the getElementById() method. This method returns a node object.

Syntax:
document.getElementById(id)
Among them, id is the id attribute of the HTML tag.

For example, the statement to obtain the node with id="demo" is:

The return value of this statement is [object HTMLDivElement] (element node object).

For example, get several typical element nodes:

    HTML DOM树型结构图 
我是
标签

我是

标签

我是
标签

Please see the following demonstration

QQ截图20161013091511.png

QQ截图20161013091518.png

QQ截图20161013091525.png

QQ截图20161013091533.png

getElementsByTagName( ) method

To obtain DOM nodes based on HTML tag names, please use the getElementsByTagName( ) method . This method returns the obtained element node as an array.
Syntax:
nodeObject.getElementsByTagName(tagName)
Among them, nodeObject is the element node and tagName is the name of the HTML tag.
Note: The getElementsByTagName() method can not only search all nodes in the entire HTML document, but also search the child nodes of a certain node. When using it, you must specify the search range, that is, specify nodeObject.
For example, to get all the

tags in the HTML document:

document.getElementsByTagName("div");

Get all the < inside the tag with id="demo" ;div> tag:

document.getElementById("demo").getElementsByTagName("div");

For example, count the number of all

tags and display their Text:

我是第 1 个
标签
我是第 2 个
标签
我是第 3 个
标签
我是第 4 个
标签
我是第 5 个
标签
我是第 6 个
标签

Note:

getElementById() is a method of document (root node), other element nodes cannot use this method. Because the id attribute is unique in the entire HTML document, it must be searched starting from the root node.

getElementsByTagName() is a method of all element nodes, not only the document (root node) can be used, but other nodes can also be used. Therefore, to obtain DOM nodes based on HTML tag names, you can not only search from the document (root node), but also from any other element node.

Continuing Learning
||
HTML DOM树型结构图
我是第 1 个
标签
我是第 2 个
标签
我是第 3 个
标签
我是第 4 个
标签
我是第 5 个
标签
我是第 6 个
标签
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!