1
\$\begingroup\$

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));
};
\$\endgroup\$
3
  • \$\begingroup\$ Where does num_square come in? \$\endgroup\$ Commented Mar 29, 2014 at 0:33
  • \$\begingroup\$ num_square is from user input due to a prompt \$\endgroup\$ Commented Mar 29, 2014 at 0:39
  • \$\begingroup\$ It's not used anywhere in the function..? \$\endgroup\$ Commented Mar 29, 2014 at 0:42

1 Answer 1

4
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ 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? \$\endgroup\$ Commented Mar 29, 2014 at 0:47
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Commented Mar 29, 2014 at 0:57

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.