How do I add a class to a given element?

前端 未结 25 2417
清酒与你
清酒与你 2020-11-21 11:34

I have an element that already has a class:

25条回答
  •  一生所求
    2020-11-21 11:57

    You can use modern approach similar to jQuery

    If you need to change only one element, first one that JS will find in DOM, you can use this:

    document.querySelector('.someclass').className += " red";
    .red {
      color: red;
    }

    This method will add class "red" only to first element in DOM

    lorem ipsum

    lorem ipsum

    lorem ipsum

    Keep in mind to leave one space before class name.

    If you have multiple classes where you want to add new class, you can use it like this

    document.querySelectorAll('.someclass').forEach(function(element) {
      element.className += " red";
    });
    .red {
      color: red;
    }

    This method will add class "red" to all elements in DOM that have "someclass" class.

    lorem ipsum

    lorem ipsum

    lorem ipsum

提交回复
热议问题