1

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?

Alberto Rossi
  • 1,692
  • 4
  • 29
  • 54

4 Answers4

2

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?

Kamil Šrot
  • 1,992
  • 14
  • 16
1

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

ElliotM
  • 1,844
  • 2
  • 20
  • 36
0

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')
Jack
  • 340
  • 2
  • 4
0

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 }

Addendum

Class identifiers are allowed to start with a number, but ID identifiers are not.

[id='1_p'] {
 /* does work */
}

#1_p {
  /* doesn't work */
}

source

giannis christofakis
  • 7,151
  • 4
  • 48
  • 63