How to correctly use innerHTML to create an element (with possible children) from a html string?

This is similar to the answer from palswim, except that it doesn’t bother with creating a clone, and uses a while() loop instead, always appending the node at [0]. function createElement( str ) { var frag = document.createDocumentFragment(); var elem = document.createElement(‘div’); elem.innerHTML = str; while (elem.childNodes[0]) { frag.appendChild(elem.childNodes[0]); } return frag; }

Is there any major difference between innerHTML and using createTextNode to fill a span?

Of course. createTextNode will escape any strings and show them as they are, while innerHTML could render html-like strings into a DOM. If you don’t want that (unless you are sure the text contains no unescaped tags, e.g. when assigning a literal directly), you can use textContent (or innerText for IE). Yet I’d recommend createTextNode, … Read more

Remove all content using pure JS

I think a browser rightfully assumes a page with content-type text/html will always be a web page – so whilst you may do something like… document.body.innerHTML = ”; It will still have some HTML hanging around. You could try… document.documentElement.innerHTML = ”; …which left me with <html></html>. Yi Jiang did suggest something clever. window.location = … Read more

It says that TypeError: document.getElementById(…) is null [duplicate]

Make sure the script is placed in the bottom of the BODY element of the document you’re trying to manipulate, not in the HEAD element or placed before any of the elements you want to “get”. It does not matter if you import the script or if it’s inline, the important thing is the placing. … Read more

How do I clear inner HTML

The problem appears to be that the global symbol clear is already in use and your function doesn’t succeed in overriding it. If you change that name to something else (I used blah), it works just fine: Live: Version using clear which fails | Version using blah which works <html> <head> <title>lala</title> </head> <body> <h1 … Read more

tech