Based on what you said:
We were able to get the Divs by id with the command document.getElementById("nomedaiddadiv");
. Have some command that does the same, but with the Divs classes?
You want to "catch" the elements in a similar way as it already does with ids
To pick the class or ID or any CSS-compatible selector use the functions:
document.querySelector
document.querySelectorAll
Using these two functions will be much more practical than using document.getElementById
and document.getElementsByTagName
, because the selector will allow you to be much more practical.
The querySelector
takes only the first element found, for example:
console.log(document.querySelector(".foo").textContent);
console.log(document.querySelector(".bar").textContent);
console.log(document.querySelector(".baz").textContent);
<div class="foo bar baz">
Elemento 1
</div>
<div class="foo bar baz">
Elemento 2
</div>
The querySelectorAll
takes all elements found, so it will be necessary to use a for
(or forEach
, however this only in modern browsers):
var els = document.querySelectorAll(".foo");
for (var i = 0, j = els.length; i < j; i++) {
console.log(els[i].textContent);
}
<div class="foo bar baz">
Elemento 1
</div>
<div class="foo bar baz">
Elemento 2
</div>
Then to change the CSS you can create a specific class and add using .classList.add
, for example:
document.querySelector(".adicionar").onclick = function () {
document.querySelector(".foo").classList.add("novoestilo");
};
.novoestilo {
color: red;
font-weight: bold;
}
<div class="foo bar baz">
Elemento 1
</div>
<button class="adicionar">Adicionar</button>
Your question is ambiguous. Valdeir Psr’s answer starts from one premise, and Guilherme Nascimento’s from another. Which of the two things did you want to know? How to select elements based on a class, or how to change styles defined in a class? If you’re going to change styles, it’s like Valdeir explained. But it’s rare to really need it. It is usually simpler to add and remove classes from the elements.
– bfavaretto