Reputation: 53
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
Upvotes: 1
Views: 83
Reputation: 1074276
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);
Upvotes: 3