1

I need to change the style of multiple buttons with JavaScript.

I tried giving them all an ID and change it this way:

document.getElementById('button').style.color = "#ff0000";

But this of course only changed the first.

I could give them all different IDs but there are over 150 of them and that would get cumbersome.

How can I change them all?

2
  • Well you have to use different IDs. Or, give them all a class. Commented Feb 5, 2015 at 4:46
  • You can't have multiple identical IDs. Give them a class, and then apply the change to the class. Commented Feb 5, 2015 at 4:47

2 Answers 2

2

Use a common class name to all buttons and apply text styles as shown in code below.

var x = document.getElementsByClassName("btn");
for (var i = 0; i < x.length; i++) {
    x[i].style.color = "#ff0000";
}

Or give a common class name to all buttons and apply the styles using css.

.btn{
   color : #ff0000;
}
Sign up to request clarification or add additional context in comments.

Comments

0
 var selector = document.querySelectorAll(".ecard");
  • Using above we can call to all the elements with class = "ecard".
  • "querySelectorAll" can select many elements at once.
  • Replace "selector" with any term you like.
  • Replace "ecard" with the ID or CLASS of respective set of elements.

Note : We use "#" in front of a term if it is ID, and "." in front of a term if it is CLASS.

for (let index = 0; index < ec.length; index++) {
        const ecc = selector[index];
        ecc.style.backgroundColor = "#10141E"
    }

Using above code we create a loop which end after changing the background color of all the elements. In here javascript only runs above if the respective number of elements set of elements should greater than 0

  • Replace "selector" terms on above code, with term you used to replace term : selector, in first code I mentioned
  • Replace "ecc" with any term you like., and use that term to change style of multiple element

Thanks !

Comments

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.