Lord of Blood
Lord of Blood

Reputation: 35

jQuery do code if class is changed

I'm trying to check does li inside other li having class is-visible, and in that case do nothing, but if it doesn't add style width: 0px.

if (jQuery("li:has(li.is-visible)")){
    //nothing at this moment
}
else {
    jQuery('ul.cd-gallery li').css({'width' : '0px'});
}

html part of code

<ul class="cd-item-wrapper">
        <li data-type="sve" class="is-visible">
        <img class="img-reponsive" src="someimg.jpg" alt="Jabuka" height="150" />
        </li>
        <li data-type="proizvodi" class="is-hidden">
            <img class="img-reponsive" src="someimg.jpg" alt="Jabuka" height="150" />
        </li>
        <li data-type="vocnaci" class="is-hidden">
            <img class="img-reponsive" src="someimg.jpg" alt="Jabuka" height="150" />
        </li>                       
    </ul>
</li>

but I'm using jQuery to change class from is-hidden to is-visible and vice versa. So my code does not see any changes, and I have group all to display all images. If it helps here is link to that page my site

mine Jquery code is good, at least i think, but issue is (if u do inspect element on site) u see bunch of

  • and wehn u change category i need to hide elements (width:0) that dont't have li > ul > li class="is-visible"

    Upvotes: 1

    Views: 158

  • Answers (3)

    Nima Parsi
    Nima Parsi

    Reputation: 2110

    You can detect if an element has a class either by using hasClass() (which is recommended as it's fastest):

    if ( $("li > ul > li").hasClass('is-visible')) {
        //nothing at this moment
    } else {
        $('ul.cd-gallery li').css({
            'width', '0px'
        });
    }
    

    or is():

    if ( $("li > ul > li").is('.is-visible')) {
        //nothing at this moment
    } else {
        $('ul.cd-gallery li').css({
            'width', '0px'
        });
    }
    

    Upvotes: 3

    epascarello
    epascarello

    Reputation: 207557

    The check

    if (jQuery("li:has(li.is-visible)")){
    

    is always going to be true since it returns a jQuery object. Objects are truthy. It is not like getElementById which returns a falsey value. You would need to check the length.

    if (jQuery("li:has(li.is-visible)").length){
    

    Zero would be false and any number would be true.

    Other option would be to use is() or hasClass() which returns a Boolean.

    Upvotes: 0

    Sudharsan S
    Sudharsan S

    Reputation: 15403

    Use .hasClass() in jquery. The .hasClass() method will return true if the class is assigned to an element, even if other classes also are

    if(jQuery("li").hasClass('is-visible')){
    
    }
    

    Upvotes: 0

    Related Questions