87

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Erik Nelson
  • 1,019
  • 3
  • 12
  • 13

2 Answers2

445

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.

Ryan Stein
  • 7,930
  • 3
  • 24
  • 38
-2

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.

Brad Ross
  • 451
  • 8
  • 26
  • Well, I got it. I had to set padding to greater than 0. Even though its height and width are set to 64 each. Bleh. Is there any way for a child div to act like a normal div? The goal is to get each div to act like a link. Trying to create a dynamic list for a game website ;/ – Erik Nelson Dec 30 '12 at 21:24
  • 1
    I don't agree with this, innerHTML (what jquery uses for that) is *NOT* standard, and the price of not following the standard may lead to missbehaviour. Also, for me, it do not make any sense to add a plan html string into a DOM tree rather than to add node elements. – StormByte Oct 31 '13 at 13:42
  • 3
    Considering that the entire DOM tree starts out life as plain old HTML, and that innerHTML is just that - the HTML that an element has in it, having a problem with either is on par with saying you shouldn't use the DOM because it polluted the plain old HTML. – Rodney P. Barbati May 08 '14 at 04:56