0

I'm using the code like this:

document.getElementById('one').style.color = 'red';
document.getElementById('two').style.backgroundColor= 'blue';
.......
document.getElementById('another').style.fontSize= '20px';

Is there a generic method to set style for multiple id element something like below ( like jQuery ) ?

document.getElementById('one').add('two').add('three').style.color = 'red';

Or, how can I make one?

3
  • That's generally what CSS classes are for. Are you prevented from editing the HTML source? Commented Aug 21, 2014 at 10:58
  • You can use getElementsByClassName("class name"). Because Id is unique and classes can be used as common. Commented Aug 21, 2014 at 10:59
  • Can you give some sample code of your HTML markup Commented Aug 21, 2014 at 11:00

3 Answers 3

2

You can't select multiple id's in javascript once. You can do this by giving then same class name.

[ 'one', 'two', 'three' ].forEach(function( id ) {

    document.getElementById( id ).style.color = "red";

});

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. What I wanted to know is like your answer.
0

Do it through the use of CSS. set the same class for each of these elements:

<div id="one" class="class1">text</div>
<div id="two" class="class1">text</div>
<div id="three" class="class1">text</div>

CSS:

.class1 { color: blue }

then change it in Javascript with the use of JQuery like:

$('.class1').css({"color":"blue"});

It's more efficient and better understandable.

Comments

0

You can use jQuery

$("input").css('color', 'red');

You can also add class to your targeted dom elements that you want to change instead of selected all the input elements. ex:

<input id="one" class="whatever" ... etc>
<input id="two" class="whatever" ... etc>
<input id="three" class="whatever" ... etc>

And with this javascript to change them

$(".whatever").css('color', 'red');

More details about selectors at w3schools or jQuery API documentation

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.