Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 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 Answer

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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...