DEV Community

Cover image for Add class to item slider without JQuery
Kike Sanchez
Kike Sanchez

Posted on

Add class to item slider without JQuery

Alt Text

We have the following case:
We want to add a class to the banners of a slider carousel, but without considering the banners that have the class .cloned (This class is generated for the operation of the slider)

We have the following HTML:

<div class="owl-stage">
  <div class="owl-item cloned"></div>
  <div class="owl-item"></div>
  <div class="owl-item"></div>
  <div class="owl-item"></div>
  <div class="owl-item"></div>
  <div class="owl-item cloned"></div>
</div>

The javascript code would be the following:

const slider = document.querySelectorAll('.owl-stage .owl-item');
slider.forEach((comment,i) => {
    !comment.classList.contains("cloned")
        ?comment.classList.add("banner_"+i)
        :null
})

With this code we validate if it does not have the class .cloned and then we add the class we want otherwise we do nothing (null)

!comment.classList.contains("cloned")

This way our html would look like this

<div class="owl-stage">
  <div class="owl-item cloned"></div>
  <div class="owl-item banner_0"></div>
  <div class="owl-item banner_1"></div>
  <div class="owl-item banner_2"></div>
  <div class="owl-item banner_3"></div>
  <div class="owl-item cloned"></div>
</div>

There may be other ways to do it but this saved me from a hurry, I hope it helps you. And as I always say, never stop learning.

👨🏻‍💻 Enjoy code!

Top comments (0)