How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

JavascriptDom

Javascript Problem Overview


I want to create new divs as the page loads. These divs will appear as an ordered group which changes depending upon external data from a JSON file. I will need to do this with a for loop because there are over 100 divs needed.

So, I need to be able to change each created div in regards to height, width, top/left and so on. Yet, document.getElementById("created_div").style.whatever does nothing, I can't even see a single new div appear. I've set the new divs height/width to 500px, background to "red", and so on, but no new divs are definitely appearing.

What am I doing wrong?

Javascript Solutions


Solution 1 - Javascript

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

Solution 2 - Javascript

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErik NelsonView Question on Stackoverflow
Solution 1 - JavascriptRyan SteinView Answer on Stackoverflow
Solution 2 - JavascriptBrad RossView Answer on Stackoverflow