I want select all the elements with the id named singleFeed1 to singleFeed10;
for (var i=0;i<10;i++){
var post=document.getElementById('singleFeed'+i);
post.style.color='blue';
if (i==4){
post.style.color='red';
}
}
It doesn't seem to work.
my html
<li id=singleFeed1>aaaaaaaaaaaa</li>
<li id=singleFeed2>vvvvvvvvvvvv</li>
<li id=singleFeed3>dddddddddddd</li>
<li id=singleFeed4>aqqqqqqqqq</li>
<li id=singleFeed5>aaaaaddddaa</li>
......
......
Anyone has better solutions? Thanks.
asked Jul 5, 2012 at 21:34
Rouge
4,2459 gold badges32 silver badges36 bronze badges
3 Answers 3
for (var i=1;i<=10;i++){
var post=document.getElementById('singleFeed'+i);
post.style.color='blue';
if (i==4){ // you need two equal signs
post.style.color='red';
}
}
Next time check the console (i.e. firebug) and you will find these kind of errors on your own.
Danilo Valente
11.4k9 gold badges55 silver badges71 bronze badges
answered Jul 5, 2012 at 21:37
Chris
4,38410 gold badges47 silver badges87 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Styxxy
Start i from 1 till 10 (<=) and you should be all right with your code.
for (var i=1;i<=10;i++){
var post=document.getElementById('singleFeed'+i);
post.style.color='blue';
if (i===4){
post.style.color='red';
}
}
In your original code you try to get 0-9 instead of 1-10.
answered Jul 5, 2012 at 21:38
CD..
74.4k25 gold badges160 silver badges170 bronze badges
Comments
In my opinion, @Chris has the right answer. However, I would do something like this:
HTML
<li id=singleFeed1 class="singleFeed">aaaaaaaaaaaa</li>
<li id=singleFeed2 class="singleFeed">vvvvvvvvvvvv</li>
<li id=singleFeed3 class="singleFeed">dddddddddddd</li>
<li id=singleFeed4 class="singleFeed">aqqqqqqqqq</li>
<li id=singleFeed5 class="singleFeed">aaaaaddddaa</li>
Javascript
var posts=document.getElementsByClassName('singleFeed');
for(var i=0;i<posts.length;i++){
posts[i].style.color='blue';
if(i==4){
posts[i].style.color='red';
}
}
answered Jul 5, 2012 at 21:41
Danilo Valente
11.4k9 gold badges55 silver badges71 bronze badges
Comments
lang-js
if (i=4)should actually beif (i === 4)