Niro* by cho45

#1 Advantage of createElementFromString over jQuery

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.


'template1' is a string contains following:

<div class="entry">
	<h2 class="title">#{title}</h2>
	<div class="body">
	<div class="info">
		<span class="datetime">#{datetime}</span>
		<span class="author">#{author}</span>

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.datetime //=> span.datetime   //=>


[[javascript]] [[snippet]]

blog comments powered by Disqus