DirtyyyDan
DirtyyyDan

Reputation: 85

Javascript: Change multiple Element styles by ID

I'm actually working on a darkmode and have a problem to change the css of more than one element.

JS code:

      var elem = document.getElementById('fonts');
      for(var i=0; i<elem.length; i++){
        elem[i].style.color="#FFFFFF";
        console.log(elem[i]);
      }

But nothing changes.. i think i need to do it with the loop because i got more elements with the id "fonts". If i do it without the loop, than will only change the first one.

The console dont give an error or anything.. did i something wrong?

Upvotes: 1

Views: 1027

Answers (3)

Momin
Momin

Reputation: 3320

We can also use the for...of statement to simplified the code and increase more readability

document.getElementById("btn").addEventListener("click", function() {
  let elem = document.querySelectorAll('.fonts');

  for (let font of elem) {
    font.style.color = "#00aeff";
  }
});
* {
  margin: 0;
  padding: 0;
}
<h1 class="fonts">Heading1</h1>
<p class="fonts">Paragraph</p>
<span class="fonts">Span</span>
<div class="fonts">Div</div>

<button id="btn">Change</button>

Upvotes: 0

Aditya
Aditya

Reputation: 1329

Well you are doing it the wrong way, firstly you can use same id for multiple elements instead you have to use a class

So check this out

document.getElementById("btn").addEventListener("click", function() {
  var elem = document.querySelectorAll('.fonts');

  for(var i=0; i<elem.length; i++){
    elem[i].style.color = "#00aeff";
    console.log(elem[i]);
  }
});
* { margin: 0; padding: 0; }
<h1 class="fonts">Heading1</h1>
<p class="fonts">Paragraph</p>
<span class="fonts">Span</span>
<div class="fonts">Div</div>

<button id="btn">Change</button>

And the CSS and button are not necessary it's just for example, you use querySelectorAll to select all the elements with same class or whatever and then run a for loop on those elements

Upvotes: 2

Nissrine
Nissrine

Reputation: 1

you can only use the <div id="fonts"> once. so if you have it multiple times in your html your code won't work..

  1. change id's to classes

  2. try your code try using the HTML DOM "querySelector" instead of "getElementById".

for an id use this syntax

  var elem = document.querySelector("#fonts");

for a class use this syntax

var elem = document.querySelector(".fonts");

Upvotes: 0

Related Questions