HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
The getElementsByTagName() method returns an HTMLCollection object
The getElementsByTagName()
method returns an HTMLCollection
object.
An HTMLCollection
object is
an array-like list (collection) of HTML elements.
The following code selects all <p>
elements in a document:
const myCollection = document.getElementsByTagName("p");
The elements in the collection can be accessed by an index number.
To access the second <p> element you can write:
myCollection[1]
The length
property defines the number of elements in an HTMLCollection
:
myCollection.length
The length
property is useful when you want to loop through the elements in a
collection:
Change the text color of all <p> elements:
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
An HTMLCollection is NOT an array!
An HTMLCollection may look like an array, but it is not.
You can loop through the list and refer to the elements with a number (just like an array).
However, you cannot use array methods like valueOf(), pop(), push(), or join() on an HTMLCollection.