Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - How to dynamically change CSS class of an HTML tag?

I am using JavaScript. I have a variable var boolVal that either evaluates to true/false. On my page, I have a <div> tag:

<div id='div1' class="redClass"></div>

Based on the value of var boolVal, I want to change the CSS class of the <div> tag to blueClass.

For example: present class makes <div> color red, then the new class should make the page blue at runtime without need for page refresh.

Can we achieve this in simple JavaScript? Can we use

document.getElementById("MyElement").className = "MyClass";

or should we use AddClass?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add a CSS class based on id dynamically using classList API as follows:

document.getElementById('idOfElement').classList.add('newClassName');

Or the old way:

document.getElementById('idOfElement').className = 'newClassName';
// += to keep existing classes

Alternatively you can use other DOM query methods shown below to find elements. The last three return a collection so you'll have to iterate over it and apply the class to each element in the collection (similar to the example given below each).


In your case

var element = document.getElementById('div1');
if(boolVal)
   element.className= 'blueClass'; // += ' blueClass'; to keep existing classes
else
   element.className= 'redClass';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...