Changing CSS by class in Javascript, is it possible?

Asked

Viewed 2,255 times

2

I wonder if it is possible to make changes to the CSS of a class by Javascript. 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 classes of Divs?

Thank you.

  • 1

    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.

4 answers

2

I wonder if it is possible to make changes to the CSS of a class by Javascript.

Yes, it is possible to change CSS classes through Javascript, for this you just need to use document.styleSheets[indice].cssRules, this code will list all classes of a given <style> or <link>.

This code will give you access to the API Cssrule, with this you can change your CSS class through Javascript.

Example:

const classeQueDesejoAlterar = ".italic";

/* Percorre todas as regras CSS do primeiro Stylesheet da página */
let cssRuleList = [...document.styleSheets[0].cssRules].filter( rule => rule.selectorText == classeQueDesejoAlterar)

/* Percorre todas as regras capturadas e aplica o CSS */
for (let cssRule of cssRuleList) {
  cssRule.style.setProperty("background", "red")
}
h1 {font-size: 50%}

.italic {font-style:italic}
<h1>StackOverflow</h1>
<p class="italic">Teste</p>

Of course this code works well when you know the order of CSS, but if you don’t know, you can create a function to list all the CSS of the page, for example:

const classeQueDesejoAlterar = ".italic";

/* Lista e percorre todos os Stylesheet da página */
for (let stylesheet of document.styleSheets) {

  /* Lista e filtra a regra do CSS */
  let cssRuleList = [...document.styleSheets[0].cssRules].filter(rule => rule.selectorText == classeQueDesejoAlterar)

  /* Percorre todas as regras encontradas e aplica o CSS. */
  for (let cssRule of cssRuleList) {
    cssRule.style.setProperty("background", "red")
  }
}
h1 {
  font-size: 50%
}

.italic {
  font-style: italic
}
<h1>StackOverflow</h1>
<p class="italic">Teste</p>

1

Example: By Javascript "native":

var m = document.getElementsByTagName("div"); c = m.style;
c.color = "#c00";
c.backgroundColor = "#eee";
c.width = "200px";
c.height = "100px";
c.borderColor = "#f00";

By jQuery:

 $("div").css({
    color: "#c00",
    backgroundColor: "#eee",
    width: "200px",
    height: "100px",
    borderColor: "#f00"
});

1

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>

0

If I understand correctly, it helps!

var divId = document.getElementById('div1');
var divClass = document.getElementsByClassName('div-class');
var divElement = document.getElementsByTagName('div');



console.log('Por Id: ', divId);
console.log('Por Class: ', divClass);
console.log('Por Elemento: ', divElement);
<div id="div1" class="div-class">1</div>
<div id="div2" class="div-class">2</div>
<div id="div3" class="div-class">3</div>
<div id="div4" class="div-class">4</div>

Note: If you want to get a specific element in cases where more than one element is found, treat it as an array, example: divElement[0]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.