简体   繁体   中英

jQuery How to add a class to a div if another div has specific class

if any of the webpage elements has is-open class, add open class to another div. doesn't work

is-open is added to div's each time a modal or tab is opened on the page.

<script>
if($(".is-open").length){
$(".blur-screen").addClass("open");
} else {
$(".blur-screen").removeClass("open");    
}        
</script>

The code in your script runs immediately (before is-open is added to a div, because that only happens if a modal or tab is open, which probably doesn't happen immediately when page is loaded).

what you need to do is to call a function that will check it every time a modal/tab is opened

function checkIsOpen() {
  if($(".is-open").length){
    $(".blur-screen").addClass("open");
  } else {
    $(".blur-screen").removeClass("open");    
  }        
}

when modal/tab opens:

checkIsOpen();

Try this,

if($("div").hasClass('is-open')){
  $(".blur-screen").addClass("open");
} else {
  $(".blur-screen").removeClass("open");    
} 

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