-2

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?

3 Answers3

1

You can hide #product-recommender-recipe and check if .slick-initialized exists than show using just CSS.

it is working perfectly.

#product-recommender-recipe {
  padding: 50px;
  background-color: red;
  display: none;
}

#product-recommender-recipe:has(.slick-initialized) {
  display: block;
}
<!-- hidden if slick-initialized not exist -->
<div id="product-recommender-recipe">
<!-- <div class="slick-initialized"></div> -->
</div>
<br/>
<!-- visible if slick-initialized exist -->
<div id="product-recommender-recipe">
  <div class="slick-initialized"></div>
</div>
ahmed moeed
  • 183
  • 6
  • @SchneiderG did you manage to fix it? here is my simple answer for your question. if you would like please voteup for appreciation.thanks – ahmed moeed Jan 18 '23 at 22:06
0

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>
Guy Nachshon
  • 2,411
  • 4
  • 16
0

getElementsByClassName expects a single class name – not a selector. If you want to use a selector, use querySelector or querySelectorAll. querySelector returns null if the element doesn't exists in the DOM.

const element = document.querySelector(".slick-initialized");

if(element === null) {
    document.querySelector("#product-recommender-recipe").style.display = "none";
}
Suboptimierer
  • 554
  • 4
  • 11