Get the HTML content of the first <p> element:
const collection = document.getElementsByTagName("p").item(0);
let text = collection.innerHTML;
Try it Yourself »
This shorthand produces the same result:
const collection = document.getElementsByTagName("p")[0];
let text = collection.innerHTML;
Try it Yourself »
Change the HTML content of the first <p> element:
document.getElementsByTagName("p")[0].innerHTML = "Paragraph changed";
Try it Yourself »
More examples below.
The item()
method returns the element at a specified index in an HTMLCollection.
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.
HTMLCollection.item(
index)
HTMLCollection[
index]
Parameter | Description |
index | Required. The index of the element to return. The index starts at 0. |
Type | Description |
Element | The element at the specified index.null if the index is out of range. |
Loop over all elements with class="myclass", and change their font size:
const collection = document.getElementsByClassName("myclass");
for (let i = 0; i < collection.length; i++) {
collection.item(i).style.fontSize ="24px";
}
Try it Yourself »
Get the content of the second <p> element inside "myDIV":
const div = document.getElementById("myDIV");
const collection = div.getElementsByTagName("p");
let text = collection[1].innerHTML;
Try it Yourself »
HTMLCollection.item()
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!