3

I have the following ugly hard code:

<div class="label">
    <p id="CO-0"></p>
    <p id="CO-1"></p>
    <p id="CO-2"></p>
    <p id="CO-3"></p>
</div>

How do I use iteration in JavaScript to insert the 0, 1, 2, and 3 p id's automatically?

This is my start:

for (i = 0; i< 3; i +=1){
    $('.label').html('<p id='+[i]+'></p>');
} 

3 Answers 3

7
 for (i = 0; i < 4; i++){
       $('.label').append( '<p id="CO-'+ i +'"></p>' );
 };
Sign up to request clarification or add additional context in comments.

1 Comment

firstlu, he must defined variable, for (var i = 0; i < 4; i++){
6

While Dorin's answer is correct, for efficiency reasons, you should do the insert in one go, as DOM manipulations are relatively expensive.

var html = '';
for (var i = 0; i < 4; i++){
   html += '<p id="CO-'+ i +'"></p>';
};
$('div.label').html(html);

Comments

3

It more elegant/efficient to do all your dom insertion at once:

var inhtml ="";
for (var i = 0; i< 3; i +=1){
    inhtml += '<p id=CO-'+i+'></p>';
}

$('.label').html(inhtml);

3 Comments

removed. I just copypasted them from example. also corrected the id to more with the html i question and more valid
Should be i < 4 and while not wrong, I'm curious why you used i+=1 instead of the more common i++
again too much inspired by the question. I'd normaly do ++ just because it's shorter.

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.