FranGoitia FranGoitia - 6 months ago 19
jQuery Question

Creating Grid on the fly with jquery

I'm new to frontend and I'm trying to practice doing this simple task: I have to create a grid on the fly that is n * n (n being inputed by the user).

I succesfully created a fix sized grid, but my problem is when trying to do this dynamically.

This is the code I wrote for a 3*3 grid: http://jsfiddle.net/y7c2h8yk/

For trying to create it dynamically I wrote the following function:

var setGridDimensions = function(n) {
// emptying current grid
$(".row").empty();
var $grid = $("#grid");
for (var i = 0; i < n; i++) {
// adding row
$grid.append('<div class="row">');
// adding each to element to row
**var $row = $(".row")[i];**
for (var j = 0; j < n; j++) {
$row.append('<div class="col"></div>');
}
}
};


Now, I understand there is a problem with line
var $row = $(".row")[i]
. What I need is inside the loop first create the row, then select the row created and then loop again and create each column. How can i do that ?

Any help would be really appreciated. Thanks.

Answer

You don't have to force jQuery to search for the .row element in the DOM tree n times. You have easy way to cache the element by setting it as variable.

Another thing, is that you should empty() the whole #grid element instead of .row. empty() method remove contents of the element, but not the element itself.

Alternatively, you could remove rows using $(".row").remove();


Code (I would however use the next one)

var setGridDimensions = function(n) {
    var $grid = $("#grid").empty();
    for (var i = 0; i < n; i++) {
        // create .row and cache it setting as '$row' variable:
        var $row = $('<div class="row"/>').appendTo($grid);
        for (var j = 0; j < n; j++) {
            $row.append('<div class="col"></div>');
        }
    }
};

DEMO

This would be faster than the one above, as it's single DOM modification:

var setGridDimensions = function(n) {
    var html ='';
    for (var i = 0; i < n; i++) {
        html += '<div class="row">';
        for (var j = 0; j < n; j++) {
            html += '<div class="col"></div>';
        }
        html += '</div>';
    }
    // modify the DOM only once:
    $("#grid").html(html);
};

DEMO