jackncoke
jackncoke

Reputation: 2020

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


        });

Upvotes: 10

Views: 26756

Answers (1)

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

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

Upvotes: 27

Related Questions