Get all elements with the tag name "li":
const collection = document.getElementsByTagName("li");
Try it Yourself »
Get all elements in the document:
const collection = document.getElementsByTagName("*");
Try it Yourself »
Change the inner HTML of the first <p> element in the document:
document.getElementsByTagName("p")[0].innerHTML = "Hello World!";
Try it Yourself »
More examples below.
The getElementsByTagName()
method returns a collection of all elements with a specified tag name.
The getElementsByTagName()
method returns an HTMLCollection.
The getElementsByTagName()
property is read-only.
getElementsByTagName("*")
returns all elements in the document.
An HTMLCollection is an array-like collection (list) of HTML elements.
The elements in a collection can be accessed by index (starts at 0).
The length Property returns the number of elements in the collection.
document.getElementsByTagName(
tagname)
Parameter | Description |
tagname | Required. The tagname of the elements. |
Type | Description |
Object | An HTMLCollection object. A collection of elements with a specified tag name. The elements are sorted as they appear in the document. |
The number of <li> elements in the document:
let numb = document.getElementsByTagName("li").length;
Try it Yourself »
Change the background color of all <p> elements:
const collection = document.getElementsByTagName("P");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
Try it Yourself »
JavaScript Reference: element.getElementsByTagName()
JavaScript Tutorial: JavaScript HTML DOM Node List
document.getElementsByTagName()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!