admin管理员组文章数量:1387418
Is there a way to add a class to an element (using pure javascript) that does not have an ID, but has some existing classes? If I had:
<div class="rightAlign pushDown">...</div>
How could I add a class to make it like this
<div class="rightAlign pushDown redOutline">...</div>
This is just a simple example. The reason for adding another class and not changing the original class in CSS or changing the class altogether with javascript is that I am dealing with elements created by Dojo. I just need to access something that has no convenient ID to grab a hold of.
Keep in mind I am working in javascript and Dojo, I can not use jQuery at all...
Is there a way to add a class to an element (using pure javascript) that does not have an ID, but has some existing classes? If I had:
<div class="rightAlign pushDown">...</div>
How could I add a class to make it like this
<div class="rightAlign pushDown redOutline">...</div>
This is just a simple example. The reason for adding another class and not changing the original class in CSS or changing the class altogether with javascript is that I am dealing with elements created by Dojo. I just need to access something that has no convenient ID to grab a hold of.
Keep in mind I am working in javascript and Dojo, I can not use jQuery at all...
Share Improve this question asked Aug 1, 2013 at 22:03 user2219915user2219915 2893 gold badges7 silver badges19 bronze badges 1- what version of dojo? see dojotoolkit/reference-guide/1.7/dojo/addClass.html – Mangiucugna Commented Aug 1, 2013 at 22:06
2 Answers
Reset to default 4The dojo way would be as:
dojo.query(".rightAlign.pushDown").addClass("redOutline");
This will add the class to add elements with those two classes
var elements = document.getElementsByClassName("existing_class");
elements[0].className += " new_class";
If you want to add a class to all elements with a specified class then use a loop:
for(var i = 0; i < elements.length; i++){
elements[i].className =+ " new_class";
}
I think getElementsByClassName
doesn't work in old IE versions though.
EDIT: Polyfill for IE support
本文标签: cssjavascript Adding a class to an element that has no IDStack Overflow
版权声明:本文标题:css - javascript: Adding a class to an element that has no ID - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744521284a2610467.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论