I am using this code trying to add new content before another element:
var form = document.getElementsByClassName('commentresponse')[0],
newcomment = '<div><span></span><span><p class="author">'+author+'</p><p class="content">'+comment+'</p></span></div>' ;
form.insertBefore(newcomment, form);
The 2 vars work fine and return what I expect. However Chrome gives me this error: Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
Somehow the insertBefore line blocks the code. What am I doing wrong?
Thanks for your help guys!
insertBeforetakes a DOM node, not HTML.Do this instead:
You will want to escape
authorandcomment, as strings which contain'<','>', and'&'will mess it up.For completeness, here’s how you could do it completely with DOM nodes (without using
innerHTML— although doing such things seems to be a lost art on the modern web):This way doesn’t need to be escaped, since
authorandcontentare explicitly added as text nodes.