Red Swan
Red Swan

Reputation: 15563

Add html element to dynamically created div in javascript or jquery

I have created dynamic divs through the javascript in my asp.net mvc application. This is created in a for loop and I keep each id as an index value:

 for (j = 1; j <= count; j++) {
    $("<div id=" + j + "> Step " + j +  "</div>").
        hide().appendTo("#parentDiv").fadeIn();
 }

Now, I want to add new elements to these divs, within the same for loop. But when I am going to attach it, I am not getting the current indexed div, so that I can append it. In short, I want to render html elements dynamically in for loop on dynamically created div elements within same loop. How do I achieve this? Edited: see the real scenario is this. how to achieve?

 for (j = 1; j <= count; j++) {
    $("<div id=" + j + "> Step " + j +  "</div>").hide().appendTo("#parentDiv").fadeIn();
                    for (i = 1; i <= count; i++) {
                          $("<div id=" + i + "> Data of column " + i +  "</div>").
                         hide().appendTo("#"+j).fadeIn();
                        }

 }

Upvotes: 1

Views: 4024

Answers (4)

S L
S L

Reputation: 14328

<script src="jquery.js"></script>
<style>
#hello{
    height: 100px;
    width: 500px; 
    background: blue;
}

.small{
    margin-top: 10px;
    height: 60px;
    width: 500px;
    background: red;
}

.smallest{

    margin-top: 10px;
    height: 10px;
    width: 500px;
    background: green;

}
</style>
<script>
$(function(){
for (j = 1; j <= 5; j++) {

    var div = $("<div></div>").attr({"id": "div"+j , 'class': 'small'}).appendTo($('#hello'));
    //create some variable and add to var div
    $('<div></div>').attr({"class": 'smallest'}).appendTo(div);
    $('<div></div>').attr({"class": 'smallest'}).appendTo(div);
    $('<div></div>').attr({"class": 'smallest'}).appendTo(div);
    }




});
</script>
<div id="hello"></div>

Upvotes: 2

Shrinath
Shrinath

Reputation: 8128

you might want to take a look at this : http://api.jquery.com/live/

Upvotes: 1

Capsule
Capsule

Reputation: 6159

First you shouldn't assign just numbers to your ID, valid IDs begin with an alpha character. You should be able to reference these new objects using their respective ID later in your script. The rest of your question is cryptic...

Be careful if you are trying to attach events to these, you have to use the live() method. Classic bind() or its shortcuts click(), hover(), and so on won't work on dynamicaly added elements.

HTH

Upvotes: 2

michaelalm
michaelalm

Reputation: 210

this would work.

var count = 10
for (j = 1; j <= count; j++) {
    $("<div id=a" + j + "> Step " + j + "</div>").hide().appendTo("#parentDiv").fadeIn();
    $('#a' + j).html("test" + j);
}

Upvotes: 0

Related Questions