Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 73796

How to add and remove class from multiple elements?

$
0
0

After many-many hours trying to sort it up I gave up and came here for a help.

The idea is:

if div has a class active then images within that div should get class active. If not then images in other divs without class active should have classList.remove('active').

So the image slider should work only with images that has class pic.

I've tried many ways to solve this. But nothing is working. So far I'm trying to solve it this way:

<div class="imgSlider fade active" id="active" data="cities">

    <img src="img/cities/cities_2.jpg" id="img">
    <img src="img/cities/cities_1.jpg" id="img">
    <img src="img/cities/cities_3.jpg" id="img">
    <img src="img/cities/cities_4.jpg" id="img">

</div>
<div class="imgSlider fade" id="active" data="people">
    <img src="img/people/people_1.jpg" id="img">
    <img src="img/people/people_2.jpg" id="img">
    <img src="img/people/people_3.jpg" id="img">
    <img src="img/people/people_4.jpg" id="img">
    <img src="img/people/people_5.jpg" id="img">
    <img src="img/people/people_6.jpg" id="img">
    <img src="img/people/people_7.jpg" id="img">
    <img src="img/people/people_8.jpg" id="img">
</div>
<script>
let picture = document.getElementById('img'),
    active = document.getElementById('active');
if (active.classList.contains('active')) {
    for (let i = 0; i < picture.length; i++){
        picture[i].classList.add('pic');
     }
} else {
    for (let i = 0; i < picture.length; i++){
        picture[i].classList.remove('pic'); 
}}
</script>

Viewing all articles
Browse latest Browse all 73796

Trending Articles