2010-01-01 61 views

回答

33

嘗試這樣做...

document.getElementById("MyElement").className += " MyClass"; 

得到這個here ...

+7

您只需要用空格分隔每個類名稱:object.className ='「class1 class2 class3」' – 2015-05-27 13:18:15

6

保證可以在新的瀏覽器上工作。舊的className方式可能不會,因爲它已被棄用。

<element class="oneclass" /> 

element.setAttribute('class', element.getAttribute('class') + ' another'); 
alert(element.getAttribute('class')); // oneclass another 
21

這工作:

myElement.className = 'foo bar baz'; 
2

也許:

document.getElementById("myEle").className = "class1 class2"; 

沒有測試,但應該工作。

1

試試這個:

function addClass(element, value) { 
    if(!element.className) { 
    element.className = value; 
    } else { 
    newClassName = element.className; 
    newClassName+= " "; 
    newClassName+= value; 
    element.className = newClassName; 
    } 
} 

類似的邏輯可以用來做removeClass功能。

1

只是用這個

element.getAttributeNode("class").value += " antherClass"; 

照顧大約空間,以避免與新類

1

混合老班在現代瀏覽器中,classList APIsupported

這允許(香草)JavaScript函數是這樣的:

var addClasses; 

addClasses = function (selector, classArray) { 
    'use strict'; 

    var className, element, elements, i, j, lengthI, lengthJ; 

    elements = document.querySelectorAll(selector); 

    // Loop through the elements 
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) { 
     element = elements[i]; 

     // Loop through the array of classes to add one class at a time 
     for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) { 
      className = classArray[j]; 

      element.classList.add(className); 
     } 
    } 
}; 

現代瀏覽器(未IE)支持傳遞多個參數到classList::add功能,這將消除對於嵌套循環的需要,簡化了起作用的位:

var addClasses; 

addClasses = function (selector, classArray) { 
    'use strict'; 

    var classList, className, element, elements, i, j, lengthI, lengthJ; 

    elements = document.querySelectorAll(selector); 

    // Loop through the elements 
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) { 
     element = elements[i]; 
     classList = element.classList; 

     // Pass the array of classes as multiple arguments to classList::add 
     classList.add.apply(classList, classArray); 
    } 
}; 

使用

addClasses('.button', ['large', 'primary']); 

功能版本

var addClassesToElement, addClassesToSelection; 

addClassesToElement = function (element, classArray) { 
    'use strict'; 

    classArray.forEach(function (className) { 
     element.classList.add(className); 
    }); 
}; 

addClassesToSelection = function (selector, classArray) { 
    'use strict'; 

    // Use Array::forEach on NodeList to iterate over results. 
    // Okay, since we’re not trying to modify the NodeList. 
    Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) { 
     addClassesToElement(element, classArray) 
    }); 
}; 

// Usage 
addClassesToSelection('.button', ['button', 'button--primary', 'button--large']) 

classList::add功能將防止相同的CSS類的多個實例,而不是以前的一些答案。在班級列表API

資源:

7
var el = document.getElementsByClassName('myclass') 

el[0].classList.add('newclass'); 

el[0].classList.remove('newclass'); 

要查找類是否EXIS TS與否,使用:

el[0].classList.contains('newclass'); // this will return true or false 

支持的瀏覽器IE8 +

+1

http://caniuse.com/#feat=classlist IE10 + .. – poxip 2015-08-20 10:11:31

13

這裏有一個通過classList(所有現代瀏覽器都支持,在其他的答案提到這裏)來添加多個類簡單的方法:

div.classList.add('foo', 'bar'); // add multiple classes

來源: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples

如果你有一個ARR AY的類名添加到一個元素,你可以使用ES6 spread operator通過這一個班輪將它們全部傳遞到classList.add()

let classesToAdd = [ 'foo', 'bar', 'baz' ]; 
div.classList.add(...classesToAdd); 

請注意,並非所有的瀏覽器都支持ES6本身還,所以與任何其他ES6回答你可能會想要使用像Babel這樣的轉譯器,或者只是堅持使用ES5並使用像上面的@ LayZee的解決方案。

0

也許這會幫助你學習:

//<![CDATA[ 
 
/* external.js */ 
 
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere 
 
addEventListener('load', function(){ 
 
doc = document; bod = doc.body; htm = doc.documentElement; 
 
C = function(tag){ 
 
    return doc.createElement(tag); 
 
} 
 
E = function(id){ 
 
    return doc.getElementById(id); 
 
} 
 
addClassName = function(element, className){ 
 
    var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$'); 
 
    if(!element.className.match(rx)){ 
 
    element.className += ' '+className; 
 
    } 
 
    return element.className; 
 
} 
 
removeClassName = function(element, className){ 
 
    element.className = element.className.replace(new RegExp('\s?'+className), ''); 
 
    return element.className; 
 
} 
 
var out = E('output'), mn = doc.getElementsByClassName('main')[0]; 
 
out.innerHTML = addClassName(mn, 'wow'); 
 
out.innerHTML = addClassName(mn, 'cool'); 
 
out.innerHTML = addClassName(mn, 'it works'); 
 
out.innerHTML = removeClassName(mn, 'wow'); 
 
out.innerHTML = removeClassName(mn, 'main'); 
 

 
}); // close load 
 
//]]>
/* external.css */ 
 
html,body{ 
 
    padding:0; margin:0; 
 
} 
 
.main{ 
 
    width:980px; margin:0 auto; 
 
}
<!DOCTYPE html> 
 
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> 
 
    <head> 
 
    <meta http-equiv='content-type' content='text/html;charset=utf-8' /> 
 
    <link type='text/css' rel='stylesheet' href='external.css' /> 
 
    <script type='text/javascript' src='external.js'></script> 
 
    </head> 
 
<body> 
 
    <div class='main'> 
 
    <div id='output'></div> 
 
    </div> 
 
</body> 
 
</html>

相關問題