I have a big piece of code that needs to be inserted into DOM at some point. The code also contain some variables:
<ul id="info'+value+'" class="info"><li class="hide"></li><li class="lock"><ul>
// just a piece of the code with variable "value"
Right now I am doing:
var codeToInsert = "<some code/>"
codeToInsert.insertAfter('#someID');
Is there a better way to do it from the performance point of view?
Top of my head, you can also use .append(), .appendT(), .before(), .after() etc. Check this for a range of such functions: http://api.jquery.com/category/manipulation/
If you want to insert big piece of code, use jQuery for its selector and then use the
innerHTML
DOM property - it is the fastest way to insert a big chunk of HTML. Do not wrap the string that is to be inserted into JQuery, leave it as a string.E.g.:
$('#somePlaceholder')[0].innerHTML = myHTMLString;
.http://www.quirksmode.org/dom/w3c_html.html:
If you do string concatenation in JS, create an array,
push()
the parts andjoin()
at the end instead of appending with e.g.+=
or+
. It makes a difference esp. in IE.