javascripthtmlgetelementbyidvariable-length

How to display none if div tag doesn't exist?


If the "slick-initialized" div tag doesn't exist within a parent, then I want the parent ID (product recommender-recipe) to display none. Right now this is what I have set up:

HTML is set up like this:

<div id="product-recommender-recipe">
<div class="slick-initialized">
</div>
</div>

My JS so far. If length is 0, then have the parent ID display none. :

var productTemplate = document.getElementsByClassName("#product-recommender-recipe > .slick-initialized")
                    if (productTemplate.length === 0){
                        document.getElementById("product-recommender-recipe").style.display = "none";
                    }

Do I have this set up properly?


Solution

  • You are pretty close. You have two mistakes in your implementation. The first one is that you used getElementByClassName when in fact you are using an ID as your selector. Thus you should have used querySelector.

    The second one is that you overused your selector. You have selected your parent div and placed it in a var so that you can reference it again.

    Here is my implementation:

    var productTemplate = document.querySelector("#product-recommender-recipe")
    if (!productTemplate.querySelector('.slick-initialized')) {
            productTemplate.style.display = none;
    }
    #product-recommender-recipe {
      background: red;
      width: 50px;
      height: 50px;
    }
    <div id="product-recommender-recipe">
    <div class="slick-initialized"></div>
    </div>