Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

In the code below, I take the number of square the user wants, then calculate the size of each square (so that they all fit in the container.)

I then define var square as in the 3rd line of code. I find this string pasting technique very hard to read and error-prone. The general question is thus: Is there a better way to define an element using user input?

var genGrid = function(num_square) {
    var square_size = ($(".grid_container").height() / num_grid) + "px";
    var square = "<div class='square' style='height:" + square_size + ";\
        width: " + square_size + "'></div>";

    $("body").append($(square));
};
share|improve this question
    
Where does num_square come in? –  Kvothe Mar 29 '14 at 0:33
    
num_square is from user input due to a prompt –  Heisenberg Mar 29 '14 at 0:39
    
It's not used anywhere in the function..? –  Kvothe Mar 29 '14 at 0:42

1 Answer 1

up vote 4 down vote accepted

As you have already stated passing an HTML string is not the best way to create a new DOM element. You can create a new one using plain Javascript, like this:

var newDiv = document.createElement('div');

and together with few changes to your code, function could look similar to this:

function generateGrid(numGrid) {
    var squareSize = $('.grid_container').height() / numGrid;
    var $square = $(document.createElement('div')); // we create and fetch a new element

    // here come some handy methods from jQuery, please check'em out on jquery.com
    $square.width(squareSize).height(squareSize).addClass('square');
    $('.grid_container').append($square);
}

generateGrid(4);

Hope this will help you!

share|improve this answer
    
Oh, the reason why I did not define $square as an element is because I have to append square multiple times. Can I just do var square = "(document.createElement('div'))" then? –  Heisenberg Mar 29 '14 at 0:47
1  
I have created a jsFiddle for you so you can play with the code. As you can see I've splitted this problem into two functions. One of them simply builds a square element and second one is responsible for drawing a grid. Just take a look: link –  9orky Mar 29 '14 at 0:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.