innerHTML and Event Handlers

first of all, we know that using innerHTML is quick and dirty. but if you work with skins and i18n and use templates, innerHTML is the best way to do it, because usually templates are hard to realize with DOM-structures. we think most people do not know that if you change the innerHTML-value of a node, all its children loose their event-handlers. today handgestrickt added new HTML to a node. suddenly all the other elements did not react any more. we read a little bit about this topic and found some solutions. most of them suggest to parse the HTML into a DOM-tree which is really not what we want. the best solution is a quick and dirty one, where we abuse the browsers own engine as our parser:

var foo = {
        HTML2DOM: function(HTML) {
                var fake = document.createElement('div');
                fake.innerHTML = HTML;
                var result = document.createDocumentFragment();
                var node = fake.firstChild;
                while(node) {
                        result.appendChild(node);
                        node = node.nextSibling;
                }
                return result;
        }
}

what do we do here? it is easy, we create a new node and fill in the HTML into innerHTML. then we take the result and put all its children into a fragment. tricky, eh? now we can use the appendChild()-method to append this to our desired element. the event-handlers stay untouched.

Saturday, 24. March 2007 • trackback url

Add Comment

( to reply to a comment, click the reply link next to the comment )

Comment Title:
Your Name:
Email Address:
Make Public?
Website:
Make Public?

Comment:


Allowed XHTML tags : a, b, i, strong, code, acrynom, blockquote, abbr. Linebreaks will be converted automatically.


Captcha:

captcha image

please type the content of the above image into the following form-field: