简体   繁体   中英

How to change the style of a CSS class with javascript?

for example, I have some Html code like this

<div class="abc"></div>

with a css stylesheet like this

.abc{display:none}

Now I would like to change the style of css class abc to display:block , how should I do it?

Would you like to change really property and value of the CSS class or just change class applied to your HTML element ?

In this case, with jQuery for example, you just have to do :

$('div').removeClass('abc').addClass('cba');

This will remove the 'abc' class currently attached to your div element and set the 'cba' class for this element.

Your 'cba' class is defined as :

.cba{display: block}

Just use simple action below

$(".abc").show(); // to display block on css
$(".abc").hide(); // to display none on css

Here full code to implement your question

<!--html code-->
<div class="abc">Hello World</div>

<!--stlyling-->
<style>
    .abc{display:none}
</style>

<!--script-->
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
    $( document ).ready(function() {
        $(".abc").show();
    });
</script>

Hope it help

For all the people saying document.getElementsByClassName('abc').style.display = 'block'; works...

How it should be:

 let e = document.getElementsByClassName('abc'); for(i = 0; i < e.length; i++){ e[i].style.display = 'block'; } 
 .abc{display:none;} 
 <div class="abc">HI!</div> <div class="abc">You can see me!</div> 

document.getElementsByClassName('abc').style.display = 'block'; method:

 document.getElementsByClassName('abc').style.display = 'block'; 
 .abc{display: none;} 
 <div class="abc">HI!</div> <div class="abc">You can see me!</div> 

Find your element in the DOM and use el.classList.remove("abc") to remove the .abc class.

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

How to find the element?

https://www.w3schools.com/js/js_htmldom_elements.asp

import jquery library using

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Use simple jquery to hide or show

$(".abc").hide();//for display none
$(".abc").show();//for display block  

IF you have one '.abc' class :

document.getElementsByClassName("abc")[0].style.display = "block";

IF you have more of one '.abc' class :

var len = document.getElementsByClassName('abc');
for(i = 0; i < len.length; i++){
  len[i].style.display = 'block';
}

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