1

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?

3
  • 3
    id is for unique element, you can use class instead, please include the HTML in the question. Commented Aug 8, 2021 at 9:34
  • Are you still have problem? @DirtyyyDan Commented Aug 9, 2021 at 12:14
  • @Danial no, its done Commented Aug 12, 2021 at 14:28

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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");

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.