2

I am building a dynamic page, on which controls are generated on the basis of what inputs are. So planing to create HTML controls using javascript.

I am concerned if i should use DOM elements or direct HTML as string.

Using DOM elements.

var div = document.createElement("div");
div.setAttribute("class","outer-div");
var input = document.createElement("input");
input.setAttriute("id","1234");
input.setAttriute("value","xyz");
div.appendChild(input);
document.body.appendChild(div);

Using HTML String

var html = "<div class='outer-div'><input id='1234' value='xyz' /></div>";
$("body").html(html);

Please suggest to choose from both.

3
  • When upvoting please consider adding criteria to choose OP meant to specify... So far both approaches are fine(and there are many others like template engine i.e. handlebars) and it is not possible to suggest one. Commented Jun 3, 2013 at 4:50
  • 1
    createDocumentFragment I believe is the best answer, with string concatenation coming in second. You can always write a jsperf and find out, or I'm sure someone has already written one... jsperf.com/dom-insert-element-vs-string/2 Commented Jun 3, 2013 at 4:56
  • Thanks for the reply guys I already used DOM elements but needed an foolproof example for the performance.. Commented Jun 3, 2013 at 5:51

1 Answer 1

1

I personally prefer to create DOM elements with jQuery like this:

var $input = $('<input>')
    .attr("id", "1234")
    .val("xyz");

var $div = $('<div>')
    .addClass('outer-div')
    .append($input)
    .appendTo(document.body);

Or use one or more DOM templates and insert/remove your customizations where necessary. However, I think this question will rather result in biased answers and debates...

Sign up to request clarification or add additional context in comments.

Comments

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.