Vennsoh Vennsoh - 5 months ago 8
HTML Question

How to appendChild a generated div under a manually created div?

I have a div element that is generated by a javascript library. Let's assume the ID for it is

auto


And I manually created a HTML div element with an ID of
manual
.

How do I move the generated
div#auto
into
div#manual
?

The div elements that are generated are not part of the document tree.
So I can't just
appendChild
to put
auto
under
manual


Any idea?



var element = document.createElement("div");
element.id = 'generated';

var el = document.getElementById('element');
console.log(el)

<div id="manual">Place #generated as child of me</div>





As you can see, I can't target the generated div element #generated because it is not in the document tree. If I can't select it, I can't place it under #manual.

Answer

In your code:

var element = document.createElement("div");
element.id = 'generated';

var el = document.getElementById('element');
console.log(el)

element is already a reference to the element. There's no reason to try to look it up again via getElementById; just use the reference you have. getElementById won't find it, because it's not in the DOM yet.

So just use element:

var element = document.createElement("div");
element.id = 'generated';

document.querySelector("#manual").appendChild(element);
// -------------------------------------------^

At that point, it's in the DOM and getElementById would find it (though, again, you don't need to; you already have a reference to it in element).

Live Example: (I've added borders and given the generated div some content to make it clear what the result is)

var element = document.createElement("div");
element.id = 'generated';
element.innerHTML = "generated";

document.querySelector("#manual").appendChild(element);
div {
  border: 1px solid black;
  padding: 2px;
}
<div id="manual">Place #generated as child of me</div>

Note that there's no need for the id on the generated div for you to do this. If you have a different reason for it having an id, that's fine, but you don't need it for this:

var element = document.createElement("div");
element.innerHTML = "generated";

document.querySelector("#manual").appendChild(element);
div {
  border: 1px solid black;
  padding: 2px;
}
<div id="manual">Place generated div as child of me</div>