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?

8
  • 2
    Share the code you use to create divs Commented Dec 30, 2012 at 21:13
  • 1
    $("#box0").append('<div id="created_div"></div>'); Commented Dec 30, 2012 at 21:13
  • If you're doing this in a loop, does that mean you're attempting to create 100 divs with the same identifier? Commented Dec 30, 2012 at 21:14
  • look in browser console...any errors? Even though ID should not be repeated...shouldn't stop it being inserted if selector exists and no errors thrown.Errors are first critical check Commented Dec 30, 2012 at 21:14
  • besides creating them, do you insert them in the DOM ? Commented Dec 30, 2012 at 21:17

2 Answers 2

446

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.

Sign up to request clarification or add additional context in comments.

Comments

-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.

3 Comments

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 ;/
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.