Reputation: 306
I am trying to do logic using javascript, so that if div where class is b-format if innerhtml value is Audio it will hide cart-button div, else it will hide the more-button div. For some reason its not working.
var itemButtons = document.querySelectorAll('.slider-wrapper');
for(var i=0; i<itemButtons.length; i++){
var b_format_element = itemButtons[i].getElementsByClassName("b-format")[0];
var cart_element = itemButtons[i].getElementsByClassName("cart-button")[0];
var more_element = itemButtons[i].getElementsByClassName("more-button")[0];
if(b_format_element.innerHTML == "Audio"){
cart_element.style.display = "none";
} else {
more_element.style.display = "none";
}
}
this is html code
<div class="slider-wrapper">
${#Recommend} // this repeat record
<a class="product" href="#">
<div>
<p class="b-format">Audio</p>
</div>
<div class="product-items cart-button">
<span>Read more</span>
</div>
<div class="product actions product-items more-button">
<span>Read more</span>
</div>
</a>
${/Recommend}
</div>
Upvotes: 0
Views: 54
Reputation: 23654
Not good idea to use the same ID tags over and over in a loop. Instead, use a class name. Also, using querySelector
will get you the first matching element. It also looks like you want to cycle through the inner DIVs of the slider-container, rather than cycling through multiple slider containers. I added an inner container .record
.
document.querySelectorAll('.slider-wrapper .record').forEach(c => {
let isAudio = c.querySelector('.b-format')?.innerText.trim() === 'Audio';
c.querySelector('.cart-button').style.display = isAudio ? 'none' : 'block';
c.querySelector('.more-button').style.display = !isAudio ? 'none' : 'block';
})
.cart-button {
color: #f00;
}
.more-button {
color: #999;
}
<div class="slider-wrapper">
<div class='record'>
<div>
<p class="b-format">Audio</p>
</div>
<!-- buttom -->
<div class="cart-button">
<span>Les mer</span>
</div>
<div class="more-button">
<span>Les mer</span>
</div>
<!-- button end -->
</div>
<div class='record'>
<div>
<p class="b-format">Not Audio</p>
</div>
<!-- buttom -->
<div class="cart-button">
<span>Les mer</span>
</div>
<div class="more-button">
<span>Les mer</span>
</div>
<!-- button end -->
</div>
</div>
Upvotes: 2