javascript, hot to toggle multiple <div class="oldwidth"> with getElementsByClassName and classList.toggle

Javascript,

  1. Click on DIV with the class="oldwidth",
  2. Then change ALL to class="newwidth"
    how to?

From this:

<div class="oldwidth">sample 1 text</div>
<div class="oldwidth">sample 2 text</div>
<div class="oldwidth">sample 2 text</div>
<div class="oldwidth">sample 3 text</div>

to this:

<div class="newwidth">sample 1 text</div>
<div class="newwidth">sample 2 text</div>
<div class="newwidth">sample 2 text</div>
<div class="newwidth">sample 3 text</div>

I got it half working, but it wil change only 1 and not all.
Will result to:

<div class="**newwidth**">sample 1 text</div>
<div class="oldwidth">sample 2 text</div>
<div class="oldwidth">sample 2 text</div>
<div class="oldwidth">sample 3 text</div>

<script>
var element = document.getElementsByClassName("oldwidth")[0];
element.classList.toggle("newwidth");
</script>

Solution (?):

var element = document.querySelector('.oldwidth');
element.classList.toggle("newwidth");

But it still toggles only once and only the first.

>Solution :

almost, your current code only targets the first element with the class "oldwidth" and toggles its class to "newwidth". To change all elements with the class "oldwidth", you need to loop through each of them and toggle their classes.

<div class="oldwidth">sample 1 text</div>
<div class="oldwidth">sample 2 text</div>
<div class="oldwidth">sample 2 text</div>
<div class="oldwidth">sample 3 text</div>

<script>
var elements = document.getElementsByClassName("oldwidth");

for (var i = 0; i < elements.length; i++) {
    elements[i].classList.toggle("newwidth");
}
</script>

Leave a Reply