Consider the snippet below:
var element = document.createElement(null);
console.log(element);
document.body.appendChild(element);
console.log(element);
element.outerHTML = "<div id='hi'> hello there </div>";
console.log(element);
element = document.getElementById("hi");
console.log(element);
What you'll notice is that the reference is to the original element, after outerHTML
is used. This is as stated in the documentation:
Also, while the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element.
Thus, the easiest way is to actually use document.getElementById()
after setting said id
to get the new element that was created or using document.createElement()
like this to create a less generic object and manipulating its innerHTML()
:
var element = document.createElement('div');
console.log(element);
element.innerHTML = ' hello there ';
document.body.appendChild(element);
console.log(element);
As you can see, in the above snippet, element
is the same after changing its content.
Update:
Using some creative trickery, you can add the stuff you want using innerHTML
to the generic element you create, then grab its firstChild
and replace element
, then finally add it to your document and keep it selected. The example below shows you how to do this:
var element = document.createElement(null);
element.innerHTML = '<div> hello there </div>';
element = element.firstChild;
document.body.appendChild(element);
console.log(element);
replaceWith
method, and the ol'good replaceChild which would probably be cleaner. (wrap your new element in an off-doc div, set its innerHTML to the wanted one, then replace your old<null>
with the off-doc div's content. – Decasyllable