views:

34

answers:

1

I found a large number of browser-side JavaScript templates which render a template with data values a string. However, I'm a bit uncertain how this string is supposed to be translated to display elements in the DOM.

Obviously, one way is just document.write - but I think that has been long buried since.

Another is using element.innerHTML, but atleast some years ago this was not part of any standard, and it didn't work for XHTML-documents.

So, what's the deal nowadays? Is .innerHTML the one to use and that works perfectly for XHTML and is a part of a standard? Or do people just use it and it works? Or is there something else that is supported?

As an aside, PURE.js seems to be all about building templates out of DOM-elements, which seems pretty attractive to me - are there any other template engines which work the same way?

+4  A: 

innerHTML works pretty much everywhere.

These methods are also useful for working with the DOM which is basically what a template engine needs to do:

  • createElement
  • appendChild
  • createTextNode
  • removeChild
  • parentNode

libraries like jQuery make extensive use of these.

Moin Zaman
I believe `innerHTML` also tends to be really fast, compared to your usual DOM methods. (Insert premature optimisation warning.) When you think about it, `innerHTML` takes a string, and turns it into a DOM node, which is what browsers do whenever they load a web page. If a browser doesn’t do that fast, it’s in trouble.
Paul D. Waite
@Paul In Chrome DOM is faster than `innerHTML`, in Firefox they're about the same, and in IE `innerHTML` is much, much faster.
indieinvader
@indieinvader: huh, good to know. Have you got any sources? The tests I can find suggests there’s not much difference between DOM methods and innerHTML in non-IE browsers. 1) http://andrew.hedges.name/experiments/innerhtml/ 2) http://blog.nqzero.com/2009/11/javascript-rendering-performance.html
Paul D. Waite