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.
$(document).ready(function () {
var ClassBtn = document.getElementsByClassName("buttonSubmit");
ClassBtn.className = ClassBtn.className + " btn";
});
In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.
Using . add() method: This method is used to add a class name to the selected element. Syntax: element.
If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size. CSS Classes will help you stylize HTML elements quickly.
Since it appears you are using jQuery:
Live Demo
$(document).ready(function () {
$('.buttonSubmit').addClass('btn');
});
Without jQuery:
Live Demo
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With