0

I'm trying to create the following html dynamically with JS, but couldn't quite make the loop work.

I'll receive the count value (i.e: 1, 2, 3, etc.) from a user input.

<div class='outer-1'>
    <div class='inner-1'></div>
</div>
<div class='outer-2'>
    <div class='inner-1'></div>
    <div class='inner-2'></div>
</div>
<div class='outer-3'>
    <div class='inner-1'></div>
    <div class='inner-2'></div>
    <div class='inner-3'></div>
</div>
........

This is what I've so far:

var html = '';
for (var i = 1; i <= count; i++) {
    html += "<div class='outer-"+ i +"'>";
    html += "<div class='inner"-"+ i +"'></div>";
    html += "</div>";
}

That code only prints like below.

<div class='outer-1'>
    <div class='inner-1'></div>
</div>
<div class='outer-2'>
    <div class='inner-2'></div>
</div>

4 Answers 4

4

You need an inner loop to generate the contents of each outer <div>.

var html = '';
for (var i = 1; i <= count; i++) {
    html += "<div class='outer-"+ i + "'>";
    for (var j = 1; j <= i; j++) {
        html += "<div class='inner-" + j + "'></div>";
    }
    html += "</div>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome; glad to be of service. It looks like you're new to Stack Overflow. First, welcome, and second, if an answer solves your problem it is customary to accept it. This both marks it as correct, and also provides some reputation to the user that posted it. Many users are more likely to answer questions by people who take the time to accept an answer, so this helps you as well. Cheers!
3

You need a for loop within a for loop:

var html = '';
for (var i = 1; i <= count; i++) {
    html += "<div class='outer-"+ i +"'>";
    for (var j = 1; j <= i; j++)
        html += "<div class='inner-"+ j +"'></div>";
    html += "</div>";
}

Comments

0

You need to use an outer and an inner loop:

var html = '';
for (var i = 1; i <= count; i++) {
    html += "<div class='outer-"+ i +"'>";

    for (var j = 1; j <= i; j++) {
        html += "<div class='inner"-"+ j +"'></div>";
    }

    html += "</div>";
}

Comments

0

you need a new loop for the inside divs like this :

var count=3;
var html = '';

for (var i = 1; i <= count; i++) 
{
  html += "<div class='outer-"+ i +"'>" + "\n";

 var inHtml = '';
 for (var j = 1; j <= i; j++) 
  {
    inHtml += "<div class='inner-"+ j +"'></div>" + "\n";
  }

html += inHtml;
html += "</div>" + "\n";
}

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.