class name of DOM element for native JS operation

1.classList

See MDN for details. Element.classList

add( String [, String] )
Adds the specified class value. If these classes already exist in an element's attributes, they are ignored.
remove( String [,String] )
Deletes the specified class value.
item ( Number )
Returns the class value by the index in the collection.
toggle ( String [, force] )
When there is only one parameter: switch class value; that is, if the class exists, delete it and return false; if not, add it and return true.
When the second parameter exists: if the calculation result of the second parameter is true, add the specified class value; if the calculation result is false, delete it
contains( String )
Checks whether the specified class value exists in the class attribute of the element.
replace( oldClass, newClass )
Replace an existing class with a new one.

IE10 + only has limited compatibility, does not support SVG elements, does not support toggle(), multi parameter add() and remove(), and replace()

2.className + string operation

    var classValue = element.className;
    //Add a space, otherwise you want to query "abc". If there is a class name of "abcd", there will be problems
    classValue = " " + classValue + " ";
    //query
    classValue.indexOf(" yourClassName ") === -1 ? false : true;//The same query should be followed by a space * 2
    //increase
    classValue += " yourClassName";//Note space * 1
        //or
    classValue = classVal.concat(" someClassName");//Note space * 1
    element.setAttribute("class", classValue);
    //delete
    classValue = classValue.replace(" yourClassName "," ");//Note space * 3
    element.setAttribute("class",classValue );
    //modify
    classValue = classValue.replace(" targetClassName "," yourClassName ");//Note space * 4
    element.setAttribute("class",classValue );

3.className + regular

Just like the above method, the space is replaced by regular judgment

    var element = document.querySelector('#yourId');
    //query
    function hasClass( element,yourClassName ){
    return !!element.className.match( new RegExp( "(\\s|^)" + yourClassName + "(\\s|$)") );
    // (\ \ s | ^) the judgment is preceded by a space or the start (\ \ s | $) the judgment is followed by a space or the end two exclamation marks, which are converted to Boolean values for easy judgment
    };
    //increase
    function addClass( element,yourClassName ){
    if( !hasClass( element,yourClassName ) ){
    element.className += " " + yourClassName;
    };
    };
    //delete
    function removeClass( element,yourClassName ){
        if( hasClass( element,yourClassName ) ){
            element.className = element.className.replace( new RegExp( "(\\s|^)" + yourClassName + "(\\s|$)" )," " );
        };
    };

Tags: Javascript Attribute

Posted on Mon, 02 Dec 2019 21:05:35 -0800 by thedarkwinter