Change the HTML content of the first <li> element in a list:
const list = document.getElementsByTagName("UL")[0];
list.getElementsByTagName("li")[0].innerHTML = "Milk";
Try it Yourself »
Number of <p> elements in "myDIV":
const element = document.getElementById("myDIV");
const nodes = element.getElementsByTagName("p");
let numb = nodes.length;
Try it Yourself »
Change the font size of the second <p> element in "myDIV":
const element = document.getElementById("myDIV");
element.getElementsByTagName("p")[1].style.fontSize = "24px";
Try it Yourself »
More examples below.
The getElementsByTagName()
method returns a collection of child elements with a given tag name.
The getElementsByTagName()
method returns an HTMLCollection.
A NodeList is an array-like collection (list) of nodes.
The nodes in the list can be accessed by index. The index starts at 0.
The length Poperty returns the number of nodes in the list.
element.getElementsByTagName(
tagname)
Parameter | Description |
tagname | Required. The tagname of the child elements. |
Type | Description |
NodeList | The element's child elements with the given tagname. The elements are sorted as they appear in the source code. |
Change the background color of all <p> elements inside "myDIV":
const div = document.getElementById("myDIV");
const nodes = x.getElementsByTagName("P");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "red";
}
Try it Yourself »
Change the background color of the fourth element (index 3) inside "myDIV":
const div = document.getElementById("myDIV");
div.getElementsByTagName("*")[3].style.backgroundColor = "red";
Try it Yourself »
Using the "*" parameter.
Change the background color of all elements inside "myDIV":
const div = document.getElementById("myDIV");
const nodes = div.getElementsByTagName("*");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "red";
}
Try it Yourself »
element.getElementsByTagName()
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!