Home > Software design >  Hide specific Div based on text inside another div using JavaScript
Hide specific Div based on text inside another div using JavaScript

Time:01-06

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 >
       ${#Recommend} // this repeat record
       <a  href="#">
           <div>
               <p >Audio</p>
           </div>

           <!-- buttom -->
             
               <div >
                 <span>Les mer</span>
               </div>
                                                                               
               <div >
                 <span>Les mer</span>
               </div>
                                                                           
          <!-- button end -->
       </a>
       ${/Recommend}
</div>

CodePudding user response:

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 >
  <div class='record'>
    <div>
      <p >Audio</p>
    </div>
    <!-- buttom -->
    <div >
      <span>Les mer</span>
    </div>
    <div >
      <span>Les mer</span>
    </div>
    <!-- button end -->
  </div>
  <div class='record'>
    <div>
      <p >Not Audio</p>
    </div>
    <!-- buttom -->
    <div >
      <span>Les mer</span>
    </div>
    <div >
      <span>Les mer</span>
    </div>
    <!-- button end -->
  </div>
</div>

  •  Tags:  
  • Related