lrony*
2008-10-12 20:06
采纳率: 0%
浏览 417

使用 JavaScript 更改元素的类

How can I change a class of an HTML element in response to an onClick event using JavaScript?

转载于:https://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

23条回答 默认 最新

  • 乱世@小熊 2008-10-12 20:45
    已采纳

    Modern HTML5 Techniques for changing classes

    Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

    document.getElementById("MyElement").classList.add('MyClass');
    
    document.getElementById("MyElement").classList.remove('MyClass');
    
    if ( document.getElementById("MyElement").classList.contains('MyClass') )
    
    document.getElementById("MyElement").classList.toggle('MyClass');
    

    Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

    Simple cross-browser solution

    The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

    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.)

    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 remove a class from an element:

    To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

    document.getElementById("MyElement").className =
       document.getElementById("MyElement").className.replace
          ( /(?:^|\s)MyClass(?!\S)/g , '' )
    /* Code wrapped for readability - above is all one statement */
    

    An explanation of this regex is as follows:

    (?:^|\s) # Match the start of the string, or any single whitespace character
    
    MyClass  # The literal text for the classname to remove
    
    (?!\S)   # Negative lookahead to verify the above is the whole classname
             # Ensures there is no non-space character following
             # (i.e. must be end of string or a space)
    

    The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

    To check if a class is already applied to an element:

    The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

    if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
    


    Assigning these actions to onclick events:

    Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'") this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

    The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:

    <script type="text/javascript">
        function changeClass(){
            // Code examples from above
        }
    </script>
    ...
    <button onclick="changeClass()">My Button</button>
    

    (It is not required to have this code in script tags, this is simply for brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

    The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener

    <script type="text/javascript">
        function changeClass(){
            // Code examples from above
        }
    
        window.onload = function(){
            document.getElementById("MyElement").addEventListener( 'click', changeClass);
        }
    </script>
    ...
    <button id="MyElement">My Button</button>
    

    (Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)


    JavaScript Frameworks and Libraries

    The above code is all in standard JavaScript, however it is common practise to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

    Whilst some people consider it overkill to add a ~50 KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work, or anything that might have unusual cross-browser behaviour, it is well worth considering.

    (Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

    The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

    (Note that $ here is the jQuery object.)

    Changing Classes with jQuery:

    $('#MyElement').addClass('MyClass');
    
    $('#MyElement').removeClass('MyClass');
    
    if ( $('#MyElement').hasClass('MyClass') )
    

    In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:

    $('#MyElement').toggleClass('MyClass');
    


    Assigning a function to a click event with jQuery:

    $('#MyElement').click(changeClass);
    

    or, without needing an id:

    $(':button:contains(My Button)').click(changeClass);
    


    点赞 打赏 评论
  • Didn"t forge 2008-10-12 20:12

    This is easiest with a library like jQuery:

    <input type="button" onClick="javascript:test_byid();" value="id='second'" />
    
    <script>
    function test_byid()
    {
        $("#second").toggleClass("highlight");
    }
    </script>
    
    点赞 打赏 评论
  • 三生石@ 2008-10-12 20:16

    No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.

    The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:

    Never ever change className on-the-fly !-)

    But usually you'll only need to change a property or two, and that is easily implemented:

    function highlight(elm){
        elm.style.backgroundColor ="#345";
        elm.style.color = "#fff";
    }
    
    点赞 打赏 评论
  • csdnceshi62 2009-12-08 22:15

    The line

    document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
    

    should be:

    document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
    
    点赞 打赏 评论
  • local-host 2011-05-28 07:19

    Change an element's CSS class with JavaScript in ASP.NET:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
            lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
            lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
            lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
        End If
    End Sub
    
    点赞 打赏 评论
  • 7*4 2011-05-28 07:32

    In one of my old projects that did not use jQuery, I built the following functions for adding, removing, and checking if element has class:

    function hasClass(ele, cls) {
        return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    }
    function addClass(ele, cls) {
        if (!hasClass(ele, cls)) ele.className += " " + cls;
    }
    function removeClass(ele, cls) {
        if (hasClass(ele, cls)) {
            var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
            ele.className = ele.className.replace(reg, ' ');
        }
    }
    

    So, for example, if I want onclick to add some class the the button I can use this:

    <script type="text/javascript">
        function changeClass(btn, cls) {
            if(!hasClass(btn, cls)) {
                addClass(btn, cls);
            }
        }
    </script>
    ...
    <button onclick="changeClass(this, "someClass")">My Button</button>
    

    By now for sure it would just better to use jQuery.

    点赞 打赏 评论
  • 乱世@小熊 2011-08-05 17:44

    You could also just do:

    document.getElementById('id').classList.add('class');
    document.getElementById('id').classList.remove('class');
    

    And to toggle a class (remove if exists else add it):

    document.getElementById('id').classList.toggle('class');
    
    点赞 打赏 评论
  • 妄徒之命 2011-11-26 21:04

    Just to add on information from another popular framework, Google Closures, see their dom/classes class:

    goog.dom.classes.add(element, var_args)
    
    goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)
    
    goog.dom.classes.remove(element, var_args)
    

    One option for selecting the element is using goog.dom.query with a CSS3 selector:

    var myElement = goog.dom.query("#MyElement")[0];
    
    点赞 打赏 评论
  • ℙℕℤℝ 2011-12-08 09:36

    This is working for me:

    function setCSS(eleID) {
        var currTabElem = document.getElementById(eleID);
    
        currTabElem.setAttribute("class", "some_class_name");
        currTabElem.setAttribute("className", "some_class_name");
    }
    
    点赞 打赏 评论
  • ~Onlooker 2012-01-05 19:14

    Wow, surprised there are so many overkill answers here...

    <div class="firstClass" onclick="this.className='secondClass'">
    
    点赞 打赏 评论
  • 7*4 2012-05-02 04:59

    A couple of minor notes and tweaks on the previous regexes:

    You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.

    This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.

    var s = "testing   one   four  one  two";
    var cls = "one";
    var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
    alert("[" + s.replace(rg, ' ') + "]");
    var cls = "test";
    var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
    alert("[" + s.replace(rg, ' ') + "]");
    var cls = "testing";
    var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
    alert("[" + s.replace(rg, ' ') + "]");
    var cls = "tWo";
    var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
    alert("[" + s.replace(rg, ' ') + "]");
    
    点赞 打赏 评论
  • local-host 2012-05-05 02:46

    I would use jQuery and write something like this:

    jQuery(function($) {
        $("#some-element").click(function() {
            $(this).toggleClass("clicked");
        });
    });
    

    This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.

    Yes you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.

    Thanks

    点赞 打赏 评论
  • 谁还没个明天 2012-10-17 12:21

    Here's my version, fully working:

    function addHTMLClass(item, classname) {
        var obj = item
        if (typeof item=="string") {
            obj = document.getElementById(item)
        }
        obj.className += " " + classname
    }
    
    function removeHTMLClass(item, classname) {
        var obj = item
        if (typeof item=="string") {
            obj = document.getElementById(item)
        }
        var classes = ""+obj.className
        while (classes.indexOf(classname)>-1) {
            classes = classes.replace (classname, "")
        }
        obj.className = classes
    }
    

    Usage:

    <tr onmouseover='addHTMLClass(this,"clsSelected")'
    onmouseout='removeHTMLClass(this,"clsSelected")' >
    
    点赞 打赏 评论
  • Memor.の 2013-04-11 10:13

    As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):

    HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;
    
    HTMLElement.prototype.addClass = function(string) {
      if (!(string instanceof Array)) {
        string = string.split(' ');
      }
      for(var i = 0, len = string.length; i < len; ++i) {
        if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
          this.className = this.className.trim() + ' ' + string[i];
        }
      }
    }
    
    HTMLElement.prototype.removeClass = function(string) {
      if (!(string instanceof Array)) {
        string = string.split(' ');
      }
      for(var i = 0, len = string.length; i < len; ++i) {
        this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
      }
    }
    
    HTMLElement.prototype.toggleClass = function(string) {
      if (string) {
        if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
          this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
        } else {
          this.className = this.className.trim() + ' ' + string;
        }
      }
    }
    
    HTMLElement.prototype.hasClass = function(string) {
      return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
    }
    

    And then just use like this (on click will add or remove class):

    document.getElementById('yourElementId').onclick = function() {
      this.toggleClass('active');
    }
    

    Here is demo.

    点赞 打赏 评论
  • YaoRaoLov 2014-01-18 09:28

    I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf but do not require quoting special characters in regular expressions.

    function addClass(el, cn) {
        var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
            c1 = (" " + cn + " ").replace(/\s+/g, " ");
        if (c0.indexOf(c1) < 0) {
            el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
        }
    }
    
    function delClass(el, cn) {
        var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
            c1 = (" " + cn + " ").replace(/\s+/g, " ");
        if (c0.indexOf(c1) >= 0) {
            el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
        }
    }
    

    You can also use element.classList in modern browsers.

    点赞 打赏 评论
  • 狐狸.fox 2014-04-06 06:10

    Here is simple jQuery code to do that.

    $(".class1").click(function(argument) {
        $(".parentclass").removeClass("classtoremove");
        setTimeout(function (argument) {
            $(".parentclass").addClass("classtoadd");
        }, 100);
    });
    

    Here,

    • Class1 is a listener for an event.
    • The parent class is the class which hosts the class you want to change
    • Classtoremove is the old class you have.
    • Class to add is the new class that you want to add.
    • 100 is the timeout delay during which the class is changed.

    Good Luck.

    点赞 打赏 评论
  • 谁还没个明天 2015-03-20 02:35

    Just thought I'd throw this in:

    function inArray(val, ary){
      for(var i=0,l=ary.length; i<l; i++){
        if(ary[i] === val){
          return true;
        }
      }
      return false;
    }
    function removeClassName(classNameS, fromElement){
      var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
      for(var i=0,l=s.length; i<l; i++){
        if(!iA(s[i], x))r.push(s[i]);
      }
      fromElement.className = r.join(' ');
    }
    function addClassName(classNameS, toElement){
      var s = toElement.className.split(/\s/);
      s.push(c); toElement.className = s.join(' ');
    }
    
    点赞 打赏 评论
  • 衫裤跑路 2015-10-28 07:00

    Here's a toggleClass to toggle/add/remove a class on an element:

    // If newState is provided add/remove theClass accordingly, otherwise toggle theClass
    function toggleClass(elem, theClass, newState) {
        var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
        var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
    
        elem.className=elem.className.replace(matchRegExp, ''); // clear all
        if (add) elem.className += ' ' + theClass;
    }
    

    see jsfiddle

    also see my answer here for creating a new class dynamically

    点赞 打赏 评论
  • hurriedly% 2015-11-04 17:57

    Change an element's class in vanilla JavaScript with IE6 support

    You may try to use node attributes property to keep compatibility with old browsers even IE6:

    function getClassNode(element) {
      for (var i = element.attributes.length; i--;)
        if (element.attributes[i].nodeName === 'class')
          return element.attributes[i];
    }
    
    function removeClass(classNode, className) {
      var index, classList = classNode.value.split(' ');
      if ((index = classList.indexOf(className)) > -1) {
        classList.splice(index, 1);
        classNode.value = classList.join(' ');
      }
    }
    
    function hasClass(classNode, className) {
      return classNode.value.indexOf(className) > -1;
    }
    
    function addClass(classNode, className) {
      if (!hasClass(classNode, className))
        classNode.value += ' ' + className;
    }
    
    document.getElementById('message').addEventListener('click', function() {
      var classNode = getClassNode(this);
      var className = hasClass(classNode, 'red') && 'blue' || 'red';
    
      removeClass(classNode, 'red');
      removeClass(classNode, 'blue');
    
      addClass(classNode, className);
    })
    .red {
      color: red;
    }
    .red:before {
      content: 'I am red! ';
    }
    .red:after {
      content: ' again';
    }
    .blue {
      color: blue;
    }
    .blue:before {
      content: 'I am blue! '
    }
    <span id="message" class="">Click me</span>

    </div>
    
    点赞 打赏 评论
  • 妄徒之命 2016-01-05 18:49

    Working JavaScript code:

    <div id="div_add" class="div_add">Add class from Javascript</div>
    <div id="div_replace" class="div_replace">Replace class from Javascript</div>
    <div id="div_remove" class="div_remove">Remove class from Javascript</div>
    <button onClick="div_add_class();">Add class from Javascript</button>
    <button onClick="div_replace_class();">Replace class from Javascript</button>
    <button onClick="div_remove_class();">Remove class from Javascript</button>
    <script type="text/javascript">
        function div_add_class()
        {
            document.getElementById("div_add").className += " div_added";
        }
        function div_replace_class()
        {
            document.getElementById("div_replace").className = "div_replaced";
        }
        function div_remove_class()
        {
            document.getElementById("div_remove").className = "";
        }
    </script>
    

    You can download a working code from this link.

    点赞 打赏 评论
  • 7*4 2017-04-21 02:50

    just say myElement.classList="new-class" unless you need to maintain other existing classes in which case you can use the classList.add, .remove methods.

    var doc = document;
    var divOne = doc.getElementById("one");
    var goButton = doc.getElementById("go");
    
    goButton.addEventListener("click", function() {
      divOne.classList="blue";
    });
    div{
      min-height:48px;
      min-width:48px;
    }
    .bordered{
      border: 1px solid black;
    }
    .green{
      background:green;
    }
    .blue{
      background: blue;
    }
    <button id="go">Change Class</button>
    
    <div id="one" class="bordered green">
    
    </div>

    </div>
    
    点赞 打赏 评论
  • Didn"t forge 2017-05-29 13:29

    OK, I think in this case you should use jQuery or write your own Methods in pure javascript, my preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.

    I'd like to do something like below as methods to my javascript framework to add few functionalities which handle adding classes, deleting classes, etc similar to jQuery, this is fully supported in IE9+, also my code is written in ES6, so you need to make sure your browser support it or you using something like babel, otherwise need to use ES5 syntax in your code, also in this way, we finding element via ID, which means the element needs to have an ID to be selected:

    //simple javascript utils for class management in ES6
    var classUtil = {
    
      addClass: (id, cl) => {
        document.getElementById(id).classList.add(cl);
      },
    
      removeClass: (id, cl) => {
        document.getElementById(id).classList.remove(cl);
      },
    
      hasClass: (id, cl) => {
        return document.getElementById(id).classList.contains(cl);
      },
    
      toggleClass: (id, cl) => {
        document.getElementById(id).classList.toggle(cl);
      }
    
    }
    

    and you can simply call use them as below, imagine your element has id of 'id' and class of 'class', make sure you pass them as a string, you can use the util as below:

    classUtil.addClass('myId', 'myClass');
    classUtil.removeClass('myId', 'myClass');
    classUtil.hasClass('myId', 'myClass');
    classUtil.toggleClass('myId', 'myClass');
    
    点赞 打赏 评论
  • Lotus@ 2018-09-21 09:23

    classList DOM API:

    A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:

    const el = document.getElementById("main");
    console.log(el.classList);
    <div class="content wrapper animated" id="main"></div>

    We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

    Example:

    const el = document.getElementById('container');
    
    
    function addClass () {
       el.classList.add('newclass');
    }
    
    
    function replaceClass () {
         el.classList.replace('foo', 'newFoo');
    }
    
    
    function removeClass () {
           el.classList.remove('bar');
    }
    button{
      margin: 20px;
    }
    
    .foo{
      color: red;
    }
    
    .newFoo {
      color: blue;
    }
    
    .bar{
      background-color:powderblue;
    }
    
    .newclass{
      border: 2px solid green;
    }
    <div class="foo bar" id="container">
      "Sed ut perspiciatis unde omnis 
      iste natus error sit voluptatem accusantium doloremque laudantium, 
      totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et 
      quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam 
      voluptatem quia voluptas 
     </div>
      
    <button onclick="addClass()">AddClass</button>
      
    <button onclick="replaceClass()">ReplaceClass</button>
      
    <button onclick="removeClass()">removeClass</button>
      

    </div>
    
    点赞 打赏 评论

相关推荐 更多相似问题