Javascript to change element property based on user input 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 = "&lt;div class='square' style='height:" + square_size + ";\
        width: " + square_size + "'&gt;&lt;/div&gt;";

    $("body").append($(square));
};
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!