DEV Community

Devtonight
Devtonight

Posted on • Originally published at devtonight.com

Select HTML Elements by ID, Class, Tag Name Using Vanilla JavaScript

Select An Element Using ID With getElementById()

let para3 = document.getElementById("pid3");

para3.onclick = () => {
    para3.style.backgroundColor = '#ccff00';
}
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

Select All Elements With querySelectorAll()

The querySelectorAll() method returns a NodeList.

let paragraphs = document.querySelectorAll('p');

paragraphs.forEach(paragraph => {
    paragraph.style.backgroundColor = '#ccff00';
});
Enter fullscreen mode Exit fullscreen mode

Likewise, you can also select classes and ids with querySelectorAll.

document.querySelectorAll('.para');
document.querySelectorAll('#pid4');
Enter fullscreen mode Exit fullscreen mode

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';
}
Enter fullscreen mode Exit fullscreen mode

Using forEach.

let paragraphs = document.getElementsByClassName('para');

[].forEach.call(paragraphs, function (paragraph) {
    paragraph.style.backgroundColor = '#ccff00';
});
Enter fullscreen mode Exit fullscreen mode

Using from.

let paragraphs = document.getElementsByClassName('para');

Array.from(paragraphs).forEach(paragraph => {
    paragraph.style.backgroundColor = '#ccff00';
});
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)