How do I add a class to a given element?

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

I have an element that already has a class:

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

    To add, remove or check element classes in a simple way:

    var uclass = {
        exists: function(elem,className){var p = new RegExp('(^| )'+className+'( |$)');return (elem.className && elem.className.match(p));},
        add: function(elem,className){if(uclass.exists(elem,className)){return true;}elem.className += ' '+className;},
        remove: function(elem,className){var c = elem.className;var p = new RegExp('(^| )'+className+'( |$)');c = c.replace(p,' ').replace(/  /g,' ');elem.className = c;}
    };
    
    var elem = document.getElementById('someElem');
    //Add a class, only if not exists yet.
    uclass.add(elem,'someClass');
    //Remove class
    uclass.remove(elem,'someClass');
    
    0 讨论(0)
  • 2020-11-21 11:54

    The easiest way to do this without any framework is to use element.classList.add method.

    var element = document.getElementById("div1");
    element.classList.add("otherclass");
    

    Edit: And if you want to remove class from an element -

    element.classList.remove("otherclass");
    

    I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className approach). There are some browser limitations, but you can work around them using polyfills.

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

    Shortest

    image1.parentNode.className+=' box';
    

    image1.parentNode.className+=' box';
    .box { width: 100px; height:100px; background: red; }
    <div class="someclass">
        <img ... id="image1" name="image1" />
    </div>

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

    Assuming you're doing more than just adding this one class (eg, you've got asynchronous requests and so on going on as well), I'd recommend a library like Prototype or jQuery.

    This will make just about everything you'll need to do (including this) very simple.

    So let's say you've got jQuery on your page now, you could use code like this to add a class name to an element (on load, in this case):

    $(document).ready( function() {
      $('#div1').addClass( 'some_other_class' );
    } );
    

    Check out the jQuery API browser for other stuff.

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

    I think it's better to use pure JavaScript, which we can run on the DOM of the Browser.

    Here is the functional way to use it. I have used ES6 but feel free to use ES5 and function expression or function definition, whichever suits your JavaScript StyleGuide.

    'use strict'
    
    const oldAdd = (element, className) => {
      let classes = element.className.split(' ')
      if (classes.indexOf(className) < 0) {
        classes.push(className)
      }
      element.className = classes.join(' ')
    }
    
    const oldRemove = (element, className) => {
      let classes = element.className.split(' ')
      const idx = classes.indexOf(className)
      if (idx > -1) {
        classes.splice(idx, 1)
      }
      element.className = classes.join(' ')
    }
    
    const addClass = (element, className) => {
      if (element.classList) {
        element.classList.add(className)
      } else {
        oldAdd(element, className)
      }
    }
    
    const removeClass = (element, className) => {
      if (element.classList) {
        element.classList.remove(className)
      } else {
        oldRemove(element, className)
      }
    }

    0 讨论(0)
  • 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;
    }
    <div class="someclass">
      <p>This method will add class "red" only to first element in DOM</p>
    </div>
    
    <div class="someclass">
      <p>lorem ipsum</p>
    </div>
    
    <div class="someclass">
      <p>lorem ipsum</p>
    </div>
    
    <div class="someclass">
      <p>lorem ipsum</p>
    </div>

    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;
    }
    <div class="someclass">
      <p>This method will add class "red" to all elements in DOM that have "someclass" class.</p>
    </div>
    
    <div class="someclass">
      <p>lorem ipsum</p>
    </div>
    
    <div class="someclass">
      <p>lorem ipsum</p>
    </div>
    
    <div class="someclass">
      <p>lorem ipsum</p>
    </div>

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