Be careful before setting innerHTML

When working with javascript, the most common thing a developer will do for adding content by setting innerHTML of container element.

ele.innerHTML ='<div><span>This is working fine</span>';
if(user == 'amar') {
ele.innerHTML += '<span>Hello amar welcome to your blog!</span>';
}

ele.innerHTML+='</div>';

Above code seems to be ok but there is a big mistake. Element's innerHTML is set and the div is not closed before evaluating the condition. Browser closes the div at the point and the span that is added in the condition will be sibling of div instead of child !!.

This problem can be solved by using a variable, adding the content to that variable and finally setting innerHTML to the element.

Comments

spkin2 said…
one more problem with innerHTML, i would like to add. especially in case of updating the content via Ajax, if the update content has the stylesheet included in the style tag. in IE the styles will not be applied..

workaround: you need to add a br tag to the element, before updating the content of the element via ajax

used by: popular frame works such as jquery uses this. where as prototype frame work does not use this
navya said…
Wow. This really made my day. Thanks a lot!

JavaScript Training in CHennai JavaScript Training in CHennai JQuery Online Training JQuery Online Training
HTML5 CSS3 JavaScript Training in Chennai | HTML5 Online Training

Popular posts from this blog

Proper way to have an anchor tag with onclick event

Some thoughts on MongoDB Nodejs driver

CORS issues with IE9 and workarounds