How do I insert a div into another div with plain Javascript(no JQuery or other library)?

StackOverflow https://stackoverflow.com/questions/23416957

  •  13-07-2023
  •  | 
  •  

Question

How do I insert an HTML div into another div using plain JavaScript? I have found examples of how to do this with jQuery, but I have not found out how to do it with plain JavaScript. The platform I am developing for is limited to plain JavaScript.

I would like to create a grid that has a column and row count that depends on an XML file. I wanted to create a div for each category, and for each piece of content in that category I wanted to add a div. I have been able to create a single div using the following:

document.createElement("img");

Thank you for your help.

Était-ce utile?

La solution

If you want it to be added at the bottom of an existing element, you want to use appendChild().

Start by setting the new element to a temporary variable:

var newDiv = document.createElement("div");

Then make any updates to the new element (e.g., add a class, set the id attribute, etc.) and append it to your target element:

document.getElementById.("TARGET_ID").appendChild(newDiv);

If there is other content in the target div already, and you want to place the new element in a specific location other than the end, you can identify the appropriate child element of the target div and use insertBefore() instead.

Lots of information on this can be found here: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top