Select An Element Using ID With getElementById()
let para3 = document.getElementById("pid3");
para3.onclick = () => {
para3.style.backgroundColor = '#ccff00';
}
Select The First Element With querySelector()
The querySelector()
can be used to select a particular element. But when there are multiple options, it will select the first match.
document.querySelector('#pid4').style.backgroundColor = '#ccff00';
document.querySelector('.para').style.backgroundColor = '#ccff00';
document.querySelector('p span').style.backgroundColor = '#ccff00';
Select All Elements With querySelectorAll()
The querySelectorAll()
method returns a NodeList.
let paragraphs = document.querySelectorAll('p');
paragraphs.forEach(paragraph => {
paragraph.style.backgroundColor = '#ccff00';
});
Likewise, you can also select classes
and ids
with querySelectorAll
.
document.querySelectorAll('.para');
document.querySelectorAll('#pid4');
Select All Elements With getElementsByClassName()
The getElementsByClassName()
returns an HTMLCollection object. You can use for
, forEach
and from
to loop through elements.
Using for
loop.
let paragraphs = document.getElementsByClassName('para');
for(paragraph of paragraphs) {
paragraph.style.backgroundColor = '#ccff00';
}
Using forEach
.
let paragraphs = document.getElementsByClassName('para');
[].forEach.call(paragraphs, function (paragraph) {
paragraph.style.backgroundColor = '#ccff00';
});
Using from
.
let paragraphs = document.getElementsByClassName('para');
Array.from(paragraphs).forEach(paragraph => {
paragraph.style.backgroundColor = '#ccff00';
});
Select All Elements With getElementsByTagName()
getElementsByTagName()
returns an HTMLCollection object. You can use for
, forEach
and from
to loop through elements.
let paragraphs = document.getElementsByTagName('p');
Select All Elements With getElementsByName()
getElementsByName()
returns an HTMLCollection object. You can use for
, forEach
and from
to loop through elements.
let phone_numbers = document.getElementsByName('phone_numbers');
This is a TLDR short version, visit https://devtonight.com/articles/select-html-elements-by-id-class-tag-name-using-vanilla-javascript for detailed explanations.
Latest comments (0)