how to append a css class to an element by javascript?

前端 未结 7 1926
慢半拍i
慢半拍i 2020-12-14 14:09

Suppose a HTML element\'s id is known, so the element can be refereced using:

document.getElementById(element_id);

Does a nati

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 14:42

    When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.

    Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

    document.addClass= function(el, css){
        var tem, C= el.className.split(/\s+/), A=[];    
        while(C.length){
            tem= C.shift();
            if(tem && tem!= css) A[A.length]= tem;
        }
        A[A.length]= css;
        return el.className= A.join(' ');   
    }
    

提交回复
热议问题