Reputation: 10555
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?
Upvotes: 0
Views: 4390
Reputation: 23836
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";
});
Upvotes: 2
Reputation: 1709
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
Upvotes: 0
Reputation: 2573
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.
Upvotes: 0