Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to add a CSS class to all elements with another class name

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";


        });
like image 582
jackncoke Avatar asked Aug 18 '13 01:08

jackncoke


People also ask

Can you create a CSS class in JavaScript?

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.

How do you append a class in JavaScript?

Using . add() method: This method is used to add a class name to the selected element. Syntax: element.

How do I add a class to an element in CSS?

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.


1 Answers

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"; 
    }
}
like image 138
Brandon Boone Avatar answered Sep 19 '22 05:09

Brandon Boone