How to dynamically change CSS class of DIV tag?

前端 未结 6 1226
离开以前
离开以前 2020-12-15 04:55

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

<
6条回答
  •  Happy的楠姐
    2020-12-15 05:16

    You can add a css class based on id dynamically as follows:

    document.getElementById('idOfElement').className = 'newClassName';
    

    or using classList

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

    Alternatively you can use other DOM methods like

    • querySelector
    • querySelectorAll
    • getElementsByClassName
    • getElementsByTagName

    etc 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.


    In your case

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

提交回复
热议问题