How to dynamically create a new div, change it, move, change in any way possible in JavaScript?

I want to create new div elements when the page loads. These elements are displayed as an ordered group, which changes depending on the external data from the JSON file. I need to do this with a for loop because more than 100 divs are required.

So, I need to be able to modify each div created in terms of height, width, top / left corner and so on. However, document.getElementById("created_div").style.whatever it is, I don’t even see any new div appear. I set the new divs height / width to 500px, background to "red" and so on, but no new divs definitely appear.

What am I doing wrong?

+76
javascript dom
Dec 30
source share
3 answers

This covers the basics of DOM manipulation. Remember that adding an element to a body or a node containing a body requires the newly created node to be visible inside the document.

+394
Dec 30
source share

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 labels an element with the class "container-element" (presumably the parent element into which you want to insert your divs). The add() function then inserts the HTML into the container element.

0
Dec 30
source share

in the above div.classNmae = 'col-md-6'; does not work. I already added

0
Apr 13 '19 at 4:58
source share



All Articles