10

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


        });
1
  • 5
    But why? If you're adding another class to all elements with a specific class, why not just add the same behaviours to the original element-class (assuming it's for a jQuery/JavaScript behaviour), or extend/amend the style rules in the stylesheet (if it's for styling/presentation of the elements)? The question you ask is easy enough, but it seems that there's an underlying problem that might have a better solution. Commented Aug 18, 2013 at 1:11

1 Answer 1

27

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"; 
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

In ES6, this works: [ ...document.getElementsByClassName("buttonSubmit") ].forEach( x => x.className += ' btn' )
... or alternatively, using classList and querySelectorAll: document.querySelectorAll('.buttonSubmit').forEach(x=>x.classList.add('hidden'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.