Home > Back-end >  jQuery in Wordpress - Hide parent div if it contains a specific other div
jQuery in Wordpress - Hide parent div if it contains a specific other div

Time:03-02

I'm trying to hide a slick slider section if it has no slides. I've tried tons of different options, like trying to use PHP and CSS, but I feel I'm closest to getting it to work with jQuery.

The HTML output structure is:

<div >
    <div >
        <div >
            <div >
                <div >
                
                    <div >
                        SINGLE SLIDE CONTENT
                    </div>
                    
                    <div >
                        SINGLE SLIDE CONTENT
                    </div>
                    
                    <div >
                        SINGLE SLIDE CONTENT
                    </div>
                
                </div>
            </div>
        </div>
    </div>
</div>

So, I'm thinking I can use jQuery to hide the containing div (.type-testimonials-container) if the single slide div (.slick-slide) doesn't exists.

I have tried the following:

if(jQuery(".slick-slide").html().length)
{
jQuery(".type-testimonials-container").hide();
}

As well as lots of variations of that... I think it might be because the two divs aren't on the same level and one contains the other, but trying to find a parent/child way of doing is proving difficult... I'm not sure which way to go...

Any help would be massively appreciated!

EDIT*

I've also tried checking the parent and child relationship and trying to wait until the DOM has loaded, like this:

document.addEventListener("DOMContentLoaded", function(event) {

    var parentDiv = document.getElementsByClassName("slick-track");
    var childDiv = document.getElementsByClassName("slick-slide");
    
    if (parentDiv.contains(childDiv)) 
    {
      alert("div DOES exist");
    }
    else{
      alert("div DOES NOT exist");
    }

});

But this just shows me the DOES NOT exist alert even though it does exist - Will this search the whole of the DOM for it? or do I need to provide the exact path of the div from body or something?

CodePudding user response:

Why not just query for the length of the HTML collection of .slick-slide? JQ will still return an object if the target element doesn't exist, and the object will have a property length. Something like

if(jQuery(".slick-slide").length === 0) {
  jQuery(".type-testimonials-container").hide();
}

CodePudding user response:

I managed to do it this way:

jQuery(document).ready(function() {

    if(jQuery('.slick-slide').length){
        jQuery('.type-testimonials-container').show();
    }

    else
    {
    jQuery('.type-testimonials-container').hide();
    }

});
  • Related