简体   繁体   中英

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

  • <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?

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?

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

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM