Based on what I said:
We were able to get the divs by id with the document.getElementById("nomedaiddadiv");
command. Is there any command that does the same, but with the divs classes?
You want to "catch" the elements in a similar way as you already do with ids
To grab the class or ID or any CSS selectable switch 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 that is 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 that are found, so you will need to use for
(or forEach
, however 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>
So 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>