Reputation: 1800
I have a lot of labels
I created on a php page, they all have an id like
<label id="1_p">
<label id="2_p">
<label id="3_p">
<label id="4_p">
<label id="5_p">
...I have to change their color to #D8D8D8
and I thought to do it using a for loop:
for(i=1;i<13;++i) {
document.getElementById(i+'_p').style.color='#D8D8D8';
}
By the way Firefox tells me that document.getElementById(...) is null. Any suggestion?
Upvotes: 1
Views: 334
Reputation: 2221
First of all, don't start id value by number / it's breach of HTML specification
Have a look at this answer: What are valid values for the id attribute in HTML?
Upvotes: 2
Reputation: 8321
Adding int
with string
should work. Make sure you have specified i
as var
.
As an alternative to javascript
you could use CSS3 Attribute Selectors
label[id*='_p'] {color:#D8D8D8 }
Class identifiers are allowed to start with a number, but ID identifiers are not.
[id='1_p'] {
/* does work */
}
#1_p {
/* doesn't work */
}
Upvotes: 0
Reputation: 2269
http://jsfiddle.net/fenderistic/nKuJw/
for(var i=1;i<6;i++) {
document.getElementById(i+'_p').style.color='#D8D8D8';
}
Notice I'm using i++
and not ++i
Upvotes: 1
Reputation: 370
I would add a class to all of the labels like
<label id="5_p" class="colorOrSomething">
then instead you can use the class to look them all up and change the color
document.getElementsByClassName('colorOrSomething')
Upvotes: 0