例如替代類:我有<div class="oneClass twoClass colorRed">Content</div>
,我想找到color*
類,並用新值替換顏色部分「紅」「藍」或「黃」例如,所以這將是「colorBlue
」現在......如何查找和使用JavaScript(無JQ)
我如何做,與只有JavaScript?
謝謝!
更新: 這不是我的問題:Change an element's class with JavaScript
例如替代類:我有<div class="oneClass twoClass colorRed">Content</div>
,我想找到color*
類,並用新值替換顏色部分「紅」「藍」或「黃」例如,所以這將是「colorBlue
」現在......如何查找和使用JavaScript(無JQ)
我如何做,與只有JavaScript?
謝謝!
更新: 這不是我的問題:Change an element's class with JavaScript
var node = document.getElementById('someDiv');
node.className = node.className.replace(/color.*/, 'colorBlue');
/* This css snippet will allow to see
* element's classes rendered with the html ;)*/
div:after {
content: attr(class);
margin-left: 5px;
font-style: italic;
color: gray;
}
<div id="someDiv" class="oneClass twoClass colorRed">Content</div>
選擇div標籤。 獲取div標籤的element.className,以便將類名稱作爲字符串。 使用正則表達式用colorBlue替換字符串的colorRed部分。 再次使用.className將div的類設置爲您編輯的字符串。 如果你不必支持IE,你可以使用element.classList及其方法。
分享你的研究可以幫助每個人。告訴我們你試過了什麼,以及它爲什麼不符合你的需求。這表明你已經花時間去嘗試幫助自己,它使我們避免重申明顯的答案,最重要的是它可以幫助你得到更具體和相關的答案!另請參見[如何提問] – Cerbrus
Google首次搜索結果:http://stackoverflow.com/questions/195951/change-an-elements-css-class -with的JavaScript – Drakes
[閱讀] [1] 或者別的東西,你要尋找的。 [1]:http://stackoverflow.com/questions/16510973/how-can-i-replace-one-class-with-another-on-all-elements-using-just-the-dom#答案-16511067 –