how to append a css class to an element by javascript?

前端 未结 7 1923
慢半拍i
慢半拍i 2020-12-14 14:09

Suppose a HTML element\'s id is known, so the element can be refereced using:

document.getElementById(element_id);

Does a nati

相关标签:
7条回答
  • 2020-12-14 15:04
    var element = document.getElementById(element_id);
    element.className += " " + newClassName;
    

    Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).

    Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.

    In prototype, for instance:

    // Prototype automatically checks that the element doesn't already have the class
    $(element_id).addClassName(newClassName);
    

    See how much nicer that is?!

    0 讨论(0)
提交回复
热议问题