Changing CSS by class in JavaScript, is it possible?

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 document.getElementById("nomedaiddadiv"); command. Is there any command that does the same, but with the divs classes?

Thank you.

    
asked by anonymous 14.03.2018 / 18:55

4 answers

2
  

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

Yes, you can change CSS classes through JavaScript, so you only 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 CSSRule API, so you can change your class CSS 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 fine when you know the CSS order, but in case you do not 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>
    
14.03.2018 / 19:32
1

Example: By "native" JavaScript:

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"
});
    
14.03.2018 / 19:16
1

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>
    
14.03.2018 / 19:30
0

If I understand correctly, this 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, eg: divElement[0]

    
14.03.2018 / 18:59