Omar
Omar

Reputation: 806

Check if element has CSS class. If not add it

How can I convert my jQuery lines below into Javascript. I'd like to check if this element has a class. If it doesn't have the CSS class I want to add it to the element. The lines are in asterisks below.

Jquery

    var slides = document.querySelectorAll('#slides .slide');
    var currentSlide = 0;


  function goToSlide(n){

  //Remove showing from the current slide
    var thisSlide = slides[currentSlide];

    thisSlide.classList.remove("showing");

  //get position of next slide.
    currentSlide = (n+slides.length)%slides.length;

  //Add current to next slide
    var nextSlide = slides[currentSlide];

 //Check if nextSlide has showing class. If not, add it.
  **
   if (!($(nextSlide).hasClass('showing'))) {
           $(nextSlide).addClass('showing'); 
    }
  **

    }

Upvotes: 2

Views: 4160

Answers (2)

Duy Nguyen
Duy Nguyen

Reputation: 234

check this function

function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

DEMO

Upvotes: 0

Sagar V
Sagar V

Reputation: 12478

You can use the classList and it's contains and add method.

if(!nextSlide.classList.contains(classname)){
      nextSlide.classList.add(classname);
}

function addclass(){
  if(!document.getElementById('div1').classList.contains("new")){
      document.getElementById("div1").classList.add("new");
  }
  else{
      console.log("Already exist");
  }
}
.bg-r{
  width:50px;
  height:50px;
  border:1px solid #000;
}
.new{
  background-color:#f00;
}
<div id="div1" class="bg-r"></div>
<button onclick="addclass();">Add</button>

Upvotes: 3

Related Questions