How to change a CSS class style through Javascript? (HTML5)

Send Us a Sign! (Contact Us!)
Word PDF Epub Text
XML XPS

Let's suppose you have:

<div id="mydiv" class="oldclass">text</div>

...and the following styles:

.oldclass { color: blue } .newclass { background-color: yellow }

You can change the class on mydiv in javascript like this (using, for example, an onclick event-handler):

document.getElementById('mydiv').className = 'newclass';

After the DOM manipulation you will be left with:

[tweet]

<div id="mydiv" class="newclass">text</div>

If you want to add a new CSS class without removing the old one, you can append to it:

document.getElementById('mydiv').className += ' newClass';

This will result in:

<div id="mydiv" class="oldclass newclass">text</div>

SOURCE

LINK

LANGUAGE
ENGLISH

1 thought on “How to change a CSS class style through Javascript? (HTML5)”

Comments are closed.