简体   繁体   English

使用JavaScript访问div的子节点

[英]Accessing child nodes of a div using JavaScript

I have created a div using the following code... 我使用以下代码创建了一个div ...

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

...and a second div as follows... ...以及下面的第二个div ...

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

The above divs have been created in one function. 以上div是在一个函数中创建的。 Now in another function I tried to access the first div as follows... 现在在另一个函数中,我尝试按如下方式访问第一个div ...

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

...but it produces this error: uncaught error cannot read property childnodes of null ...但会产生此错误: 未捕获的错误无法读取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 ): 您实际上必须将bannerBox div放入文档中,方法是将它传递到appendChildinsertBefore到文档中某些元素上(例如document.body ):

document.body.appendChild(bannerBox);

(But it can be any element in the document, doesn't have to be body .) (但是它可以是文档中的任何元素,不必是body 。)

Once it's in the document, you can retrieve it by id the way you've shown. 将其放入文档后,您可以按照显示的方式通过id对其进行检索。

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. 当然(这不是您遇到的问题,但这可能是下一个问题),对于bannerBox具有任何子节点(例如,对于childNodes不要将其作为空NodeList ),您需要在其中放置一些内容。 From your variable names, I'm thinking probably you'd want to put bannerAd in it, for instance: 从您的变量名来看,我想您可能想将bannerAd放入其中,例如:

bannerBox.appendChild(bannerAd);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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