使用 javascript 为所有具有另一个类名的元素添加一个 CSS 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18294759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use javascript to add a CSS class to all elements with another class name
提问by Hymanncoke
I am trying to use javascript to add a Class to all elements with a different Class. I know you might think this is redundant but for the situation i am in it is needed. i need a way to look though all elements with that class name and add the class but I don't understand how to get a count? I am working with a cms to where I cannot change the styling in the class it self.
我正在尝试使用 javascript 向具有不同类的所有元素添加一个类。我知道您可能认为这是多余的,但对于我所处的情况,这是必要的。我需要一种方法来查看具有该类名的所有元素并添加该类,但我不明白如何计算?我正在使用 cms 到我无法自行更改类中的样式的地方。
$(document).ready(function () {
var ClassBtn = document.getElementsByClassName("buttonSubmit");
ClassBtn.className = ClassBtn.className + " btn";
});
回答by Brandon Boone
Since it appears you are using jQuery:
因为看起来您正在使用jQuery:
$(document).ready(function () {
$('.buttonSubmit').addClass('btn');
});
Without jQuery:
没有 jQuery:
window.onload = function() {
var buttons = document.getElementsByClassName("buttonSubmit"),
len = buttons !== null ? buttons.length : 0,
i = 0;
for(i; i < len; i++) {
buttons[i].className += " btn";
}
}