createElementFromString is a snippet which creates DOM elements from JavaScript string. This is mostly slower than innerHTML or jQuery's $(). But sometimes, this function has advantage over them.
- Create lump of DOM tree from string
- Eg. create from template
- Do fill-in after constructing DOM
- Do bind events in inner DOM elements
As usual, jQuery's $() is used with $().find() function to retrieve event target elements. find() is very heavy function, using it many times is not a good idea. So solution of createElementFromString is not using innerHTML but parsing by self and hold elements which will be needed at a time.
Example
'template1' is a string contains following:
<div class="entry"> <h2 class="title">#{title}</h2> <div class="body"> #{body} </div> <div class="info"> <span class="datetime">#{datetime}</span> <span class="author">#{author}</span> </div> </div>
And use createElementFromString as
var t = createElementFromString(template1, { parent : document.body, data : { title : "aaa<aaa>", body : "foobar", datetime : "2008-07-19T20:26:54Z", author : "cho45" } });
Returned object has properties named with each class attribute.
t.title //=> h2.title t.body //=> div.body t.info //=> div.info t.datetime //=> span.datetime t.author //=> span.author
Benchmark
createElementFromString:
[[javascript]] [[snippet]]