Dynamically change CSS rules in JavaScript or jQuery

后端 未结 3 1605
一个人的身影
一个人的身影 2021-02-18 13:21

I\'m looking for a way to change the CSS rules of my stylesheet imported in the document. So I have an external stylesheet and some class and div attri

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-18 14:09

    You jQuery .css() method to do that.

    $('.red').css('color', 'purple');
    

    For multiple rules:

    $('.red').css({
        'color': 'purple',
        'font-size': '20px'
    });
    

    When you add dynamic element in future to DOM by the way of append, just give those element some class or id and write CSS rules like above after appending them and they will applied for all dynamically created element.

    Working sample

    Note

    Add dynamic rules is not a good solution in my point of view. Instead of the you can load some external CSS file.

    But if you need something like dynamic rules add method then:

    $('head').append(
      $('