Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading