How do I add a class to a given element?

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

I have an element that already has a class:

相关标签:
25条回答
  • 2020-11-21 12:06

    To add an additional class to an element:

    To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

    document.getElementById("MyElement").className += " MyClass";
    

    To change all classes for an element:

    To replace all existing classes with one or more new classes, set the className attribute:

    document.getElementById("MyElement").className = "MyClass";
    

    (You can use a space-delimited list to apply multiple classes.)

    0 讨论(0)
  • 2020-11-21 12:06

    I know IE9 is shutdown officially and we can achieve it with element.classList as many told above but I just tried to learn how it works without classList with help of many answers above I could learn it.

    Below code extends many answers above and improves them by avoiding adding duplicate classes.

    function addClass(element,className){
      var classArray = className.split(' ');
      classArray.forEach(function (className) {
        if(!hasClass(element,className)){
          element.className += " "+className;
        }
      });            
    }
    //this will add 5 only once
    addClass(document.querySelector('#getbyid'),'3 4 5 5 5');
    
    0 讨论(0)
  • 2020-11-21 12:08

    For those using Lodash and wanting to update className string:

    // get element reference
    var elem = document.getElementById('myElement');
    
    // add some classes. Eg. 'nav' and 'nav header'
    elem.className = _.chain(elem.className).split(/[\s]+/).union(['nav','navHeader']).join(' ').value()
    
    // remove the added classes
    elem.className = _.chain(elem.className).split(/[\s]+/).difference(['nav','navHeader']).join(' ').value()
    
    0 讨论(0)
  • 2020-11-21 12:09

    Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:

    <div class="someClass otherClass yetAnotherClass">
          <img ... id="image1" name="image1" />
    </div>
    

    From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.

    0 讨论(0)
  • 2020-11-21 12:10

    If you're only targeting modern browsers:

    Use element.classList.add to add a class:

    element.classList.add("my-class");
    

    And element.classList.remove to remove a class:

    element.classList.remove("my-class");
    

    If you need to support Internet Explorer 9 or lower:

    Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

    <div id="div1" class="someclass">
        <img ... id="image1" name="image1" />
    </div>
    

    Then

    var d = document.getElementById("div1");
    d.className += " otherclass";
    

    Note the space before otherclass. It's important to include the space otherwise it compromises existing classes that come before it in the class list.

    See also element.className on MDN.

    0 讨论(0)
  • 2020-11-21 12:12

    first, give the div an id. Then, call function appendClass:

    <script language="javascript">
      function appendClass(elementId, classToAppend){
        var oldClass = document.getElementById(elementId).getAttribute("class");
        if (oldClass.indexOf(classToAdd) == -1)
        {
          document.getElementById(elementId).setAttribute("class", classToAppend);
        }
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题