1

I have created a div using the following code...

var bannerBox = document.createElement("div");
bannerBox.id = "bannerBox";

...and a second div as follows...

var bannerAd = document.createElement("div");
bannerAd.className = "bannerAd";

The above divs have been created in one function. Now in another function I tried to access the first div as follows...

var allAds = document.getElementById("bannerBox").childNodes; 

...but it produces this error: uncaught error cannot read property childnodes of null

1 Answer 1

3

You have to actually put the bannerBox div in the document, by passing it into appendChild or insertBefore on some element that's in the document (such as document.body):

document.body.appendChild(bannerBox);

(But it can be any element in the document, doesn't have to be body.)

Once it's in the document, you can retrieve it by id the way you've shown.

And of course (this isn't the problem you're having but it could be the next problem), for bannerBox to have any child nodes (e.g., for childNodes not to be an empty NodeList), you need to put something in it. From your variable names, I'm thinking probably you'd want to put bannerAd in it, for instance:

bannerBox.appendChild(bannerAd);
Sign up to request clarification or add additional context in comments.

2 Comments

i used this document.getElementsByTagName('body')[0].appendChild(bannerBox); but it produces error cannot call method appendchild of undefined
@AmberAslam: If you used that from code within the head of the document, that could be why (there's no body yet). Moving the script tag containing the code into the body tag should sort it.

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.