简体   繁体   中英

How to hide a div element whose class name changes dynamically?

Before modal opens:

<div class="classname1">Some Text</div>

After modal closes:

<div class="classname1 classname2">Some Text</div>

You may refer my sample code.

 function addClass(){ var div=document.getElementsByClassName("classname1")[0]; div.classList.add('classname2'); }
 .classnam1{ font-weight:bold; } .classname2{ color: red; }
 <div class="classname1">Some Text</div> <button onclick="addClass()"> GO </button>

Since your question is not clear, assuming you want to add and remove the class on certain functionality.

I have created a sample fiddle using jQuery here a link !

HTML

<div class="custCls" id="banner-message">
 <div>Hello World</div>
  <button id="addStyle">Add Style</button>
  <button id="removeStyle">Remove Style</button>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

.custCls{
   width: 300px;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

jQuery

var banner = $("#banner-message")
var button = $('#addStyle');
var button1 = $('#removeStyle');

// handle click and add class
button.on("click", function(){
  banner.addClass("alt")
})

button1.on("click", function(){
  banner.removeClass("alt")
})

You can check for new classnames by getting length of classList of elements.

First set initial length of classList of element and compare.

 var initiallen = 0; var div = document.querySelector("div"); initiallen = div.classList.length; function check(){ return initiallen === div.classList.length ? false : true; }
 <div class="classname1">Some Text</div> <button onclick="document.querySelector('div').classList.add('classname2')">Add new classname</div> <button onclick='console.log("class changed?" ,check())'>Check</button>

You can add a custom attribute to that element and using it you can hide the element whenever required.

Html code.

 
 
 
<div class="classname" cust_attr="attr_1">Some Text</div>
Some Text

Jquery Code

 $("[cust_attr=attr_1]").hide();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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