newToJS
newToJS

Reputation: 11

How do I dynamically create + insert (append??) a div into a div container?

I would like it to end up as this:

<div id = "container">

<div id = "dynamicallyCreated"></div>

</div> 

I'm pretty sure that this involves either document.createElement or appendChild, but I am not quite sure how to use these to insert the newly created div into the container div.

Edit: sorry, I'm not quite sure how to do the code snippet correctly

Upvotes: 1

Views: 50

Answers (2)

Pranav Rustagi
Pranav Rustagi

Reputation: 2731

This is how you can do it :

  1. Create element using document.createElement()
  2. Add attributes (if you wish)
  3. Append it to the parent element, using appendChild().

var newEl = document.createElement('div');
newEl.setAttribute("id", "newElement");

document.querySelector("#container").appendChild(newEl);
#container {
  width: 100px;
  height: 100px;
  background: red;
}

#newElement {
  width: 50px;
  height: 50px;
  background: yellow;
}
<div id="container">
</div>

Another approach for the same can be done using innerHTML property :

document.querySelector('#container').innerHTML = "<div id='newElement'></div>"
#container {
  width: 100px;
  height: 100px;
  background: red;
}

#newElement {
  width: 50px;
  height: 50px;
  background: yellow;
}
<div id="container">
</div>

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074335

I'm pretty sure that this involves either document.createElement or appendChild

Both, actually: :-)

const div = document.createElement("div");
div.id = "dynamicallyCreated";
document.getElementById("container").appendChild(div);

More to explore on MDN: createElement, appendChild

You can also use markup if you prefer via insertAdjacentHTML:

document.getElementById("container").insertAdjacentHTML(
    "beforeend",
    "<div id='dynamicallyCreated'></div>"
);

It can add text in front of, after, at the beginning of, or at the end of an element. (Or if adding text, insertAdjacentText.)

If adding not at the end of the container, you can use insertBefore.

Upvotes: 2

Related Questions