0

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.

2
  • The first thing to notice is that you have a serious syntax error, where if (i=4) should actually be if (i === 4) Commented Jul 5, 2012 at 21:38
  • @elclanrs whoops, you caught me. Commented Jul 5, 2012 at 21:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Start i from 1 till 10 (<=) and you should be all right with your code.
2
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.

Comments

1

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';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.