About Lesson
getElementsByTagName()
Example
Get all elements with the tag name “li”:
const collection = document.getElementsByTagName("li");
Get all elements in the document:
const collection = document.getElementsByTagName("*");
Change the inner HTML of the first <p> element in the document:
document.getElementsByTagName("p")[0].innerHTML = "Hello World!";
The number of <li> elements in the document:
let numb = document.getElementsByTagName("li").length;
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";
}
getElementsByName()
Get all elements with the name “fname”:
let elements = document.getElementsByName("fname");
Number of elements with name=”animal”:
let num = document.getElementsByName("animal").length;
getElementsByClassName()
Get all elements with class=”example”:
const collection = document.getElementsByClassName("example");
Get all elements with both the “example” and “color” classes:
const collection = document.getElementsByClassName("example color");
Document getElementById()
Get the element with the specified id:
document.getElementById("demo");
Get the element and change its color:
const myElement = document.getElementById("demo");
myElement.style.color = "red";
Or just change its color:
document.getElementById("demo").style.color = "red";