简体   繁体   中英

Show Hide Div if element class loaded

I want to show the div if another div class is loaded. Show nanobar only if selected class is loaded, in other case nanobar will become hidden

css code sample:

.nanobar {
  height: 75px;
  width: 100%;
  background: #fef9c7;
  border:1px solid #fce181;
  color:#333;
  padding:10px;
  margin-bottom:10px;
  font-size: 1.2rem;
  display:none;
}

HTML code sample:

<div class="nanobar">
<span>Content</span>
</div>
<div id="category_container" class="content-padding {if $category} selected{/if}"> </div>

any help in this regards will be appreciated.

First check if you can find selected class:

var selected = document.getElementsByClassName("selected");

Then check if this variable has more then one element.

if (selected.length < 1) {

// Hide your nanobar

} else {
// Show it
}

This is not the full solution, if you still have troubles, ask in comments.

The code checks if the second div has a selected class. If so, the first div will be displayed, otherwise the first div stays hidden.

 let divElements = document.querySelectorAll('div'); if (divElements[1].classList.contains("selected")) { divElements[0].classList.replace("hide", "show"); } else { divElements[0].classList.replace("show", "hide"); }
 .nanobar { height: 75px; width: 100%; background: #fef9c7; border:1px solid #fce181; color:#333; padding:10px; margin-bottom:10px; font-size: 1.2rem; } .hide { display: none; } .show { display: block; }
 <div class="nanobar hide"> <p>Hello</p> </div> <div class="apple jason selected hide"> <p>Jason</p> </div>

Note: Removed the display property from nanobar class and made it into it's own class. Makes it easier to hide and show an element, as well as being able to reuse it for other elements.

You can read more about classList here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM