简体   繁体   中英

Accessing child nodes of a div using JavaScript

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

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 (eg, 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM