jQuery conditional that checks the class and if it contains that class it executes

I am working with wordpress and I have to display a menu based on a product category but it goes by term and there is no way for me to add a class. So I have term-maincat-subcat as the class and the subcat changes depending on where your at but the main cat stays the same as it is the brand. I was looking into the jQuery wildcards and there is a way to select an element with a certain string in a class. How would I go about running a conditional to check if it has that string in the class. Here’s what I’ve got…

if($('body').is('body[class~="brand"]')) {
   $('.brand-cat-nav').show();
}

The above doesn’t seems to work and like I said, unfortunately, there is no way of adding a straight “brand” class to it to make this a little easier with being able to just use .hasClass(). Any suggestions?

Read More

PS: the class that it’s outputting to the body is some thing to likes of “term-maincat-subcat”.

Related posts

Leave a Reply

2 comments

  1. Class is really easy to check:

    if ($('body').is('.brand')) { ... }
    

    or:

    if ($('body').hasClass('brand')) { ... }
    

    edit — if you mean that you want to find out if a string is part of a class, then that’s going to require you going to the “className” property and checking with a regex:

    if (/brand/.test($('body').prop('className'))) { ... }
    

    If it’s not always “brand”, then you can make a regular expression from a string:

    function whatever( someClassFragment ) {
      if (new RegExp(someClassFragment).test($('body').prop('className')) { ... }
    

    If the string might have non-alpha characters in it then you’d have to deal with that.

  2. You can try this:

    if( $('body').filter("[class^='brand']").length )​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ {
        // body has class starting with 'brand'
    }
    

    This filters the body with a class name that starts with ‘brand’.

    If you want to test if body has a class containing ‘brand’ use class*="brand" as filter instead.