Home > Blockchain >  If object with class X also has class Y then do
If object with class X also has class Y then do

Time:09-22

Trying to perform action when <figure> with class .woocommerce-product-gallery__wrapper has another class alongside it - .test.

This .test class is placed there by another JavaScript powered button that's toggling the class in and out. So this event would need to continue listening.

if($( ".woocommerce-product-gallery__wrapper" ).hasClass( "test" )){
console.log('Hello');
// I have the 'hidden' class
};

I feel this is something super easy and as a JS noob, I'm doing something super stupid/missing something.

CodePudding user response:

Try:

if(document.querySelector('.woocommerce-product-gallery__wrapper').classList.contains('test')){
  console.log('Hello');
};

CodePudding user response:

Consider the following.

if($(".woocommerce-product-gallery__wrapper.test" ).length > 0){
  console.log('Found Test Element');
}

This will select all elements with both classes, woocommerce-product-gallery__wrapper and test.

You can also do something like.

$(".woocommerce-product-gallery__wrapper").each(function(i, el){
  if($(el).hasClass("test")){
    console.log("Found Test, Index: "   i);
  }
});

This will iterate each element with class woocommerce-product-gallery__wrapper and check if it has the test class. This is helpful when you want to perform an action on just those elements.

You can also use .filter() like this.

$(".woocommerce-product-gallery__wrapper").filter(".test").css("background", "yellow");

There are lots of ways to find a specific element.

  • Related