DEV Community

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

Posted on

2 1

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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more