Add Remove Class to a DOM element using only JavaScript, and best of these 2 ways

前端 未结 2 1582
你的背包
你的背包 2020-12-28 21:36

What is a good approach to add class to a DOM element using JavaScript. And Remove also.

I came across this following codes for adding:

1:

2条回答
  •  梦毁少年i
    2020-12-28 22:08

    This is jquery's code.

    Adapted versions of jQuery's addClass
    And jQuery's removeClass

    If you look at jQuery source code, this is how they do it. This is adapted from them, but pretty much entirely written by jQuery and is their code. I am not the original author, and am merely showing how one piece can be used instead of the whole library.

    jQuery's addClass:

    //This code is jQuery's
    function AddClassToElement(elem,value){
     var rspaces = /\s+/;
     var classNames = (value || "").split( rspaces );
     var className = " " + elem.className + " ",
     setClass = elem.className;
     for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
      if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
       setClass += " " + classNames[c];
      }
     }
     elem.className = setClass.replace(/^\s+|\s+$/g,'');//trim
    }
    

    jQuery's removeClass:

    //This code is jQuery's
    function RemoveClassFromElement(elem,value){
     var rspaces = /\s+/;
     var rclass = /[\n\t]/g
     var classNames = (value || "").split( rspaces );
     var className = (" " + elem.className + " ").replace(rclass, " ");
     for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
      className = className.replace(" " + classNames[c] + " ", " ");
     }
     elem.className = className.replace(/^\s+|\s+$/g,'');//trim
    }
    

    Here is a working fiddle: http://jsfiddle.net/C5dvL/

提交回复
热议问题