I create a generic element by
var element = document.createElement(null);
document.body.appendChild(element);
after which, the element is altered by using outerHTML
element.outerHTML = "<div> hello there </div>";
the element displays correctly. However, the variable itself "element" does not reflect the alteration in any way. The only way to retrieve that particular element, seems to be doing something like...
element.outerHTML = "<div id='hi'> hello there </div>";
element = document.getElementById("hi");
Looks ugly. Is there any better way and/or am I missing something?
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);