Vexatu Vexx Vexatu Vexx - 3 months ago 13
Javascript Question

Append elements with childs and classes using jQuery

I'm trying to create a grid table using jQuery.
So instend of adding those elements into html page:

<div id="grid" class="gridTable">
<div class="row">
<span class="cell head"></span>
<span class="cell head"></span>
<span class="cell head"></span>
</div>
<div class="row">
<span class="cell"></span>
<span class="cell"></span>
<span class="cell"></span>
</div>
<div class="row">
<span class="cell"></span>
<span class="cell"></span>
<span class="cell"></span>
</div>
<div class="row">
<span class="cell"></span>
<span class="cell"></span>
<span class="cell"></span>
</div>
</div>


I want to add only the grid container:

<div id="grid" class="gridTable"><div>


and inside of this container to add my rows dynamically using jQuery
append()
or other method:

<div class="row">
<span class="cell head"></span>
<span class="cell head"></span>
<span class="cell head"></span>
</div>


repeating each time I want. I have tried something like:

$('.gridTable').append( $("<div></div>").addClass('row') );


but I don't know how to add
.cell
child of appended elements.

See full html code in fiddle:

Answer

Store appended element in variable and use it after append. To do this work, you need to write new element in selector and use .appendTo() to appending element.

var row = $('<div></div>').addClass("row").appendTo(".gridTable");
row.append("<span class='cell head'>col</span");
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid" class="gridTable"></div>

If you want to create all row and column of table dynamicaly, see bottom code.

for (var i = 0; i < 4; i++){
    var row = $('<div></div>').addClass("row").appendTo(".gridTable");
    for (var j = 0; j < 3; j++){
        if (i == 0)
    	    row.append("<span class='cell head'>head</span");
        else
            row.append("<span class='cell'>col</span");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid" class="gridTable"></div>

Comments