javascript - How to dynamically change CSS class of DIV tag? -


i using javascript. have variable (var boolval)that either evaluates true/false. on page have a div tag.

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

based on value of var boolval, want change css class of div tag blueclass.

for example: present class makes div color red, new class should make page blue @ runtime without need page refresh.

can achieve in simple javascript?

can use document.getelementbyid("myelement").classname = "myclass";? or should use addclass?

you can add css class based on id dynamically follows:

document.getelementbyid('idofelement').classname = 'newclassname'; 

or using classlist

document.getelementbyid('idofelement').classlist.add('newclassname'); 

alternatively can use other dom methods

etc find elements. last 3 return collection you'll have iterate on , apply class each element shown above.


in case

var element = document.getelementbyid('div1'); if(boolval)    element.classname= 'blueclass'; // += ' blueclass'; keep existing classes else    element.classname= 'redclass'; 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -