Alberto Rossi
Alberto Rossi

Reputation: 1800

Javascript change label color in a loop

I have a lot of labels I created on a php page, they all have an id like

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

Answers (4)

Kamil Šrot
Kamil Šrot

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

giannis christofakis
giannis christofakis

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 }

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

Upvotes: 0

em_
em_

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

Jack
Jack

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

Related Questions