简体   繁体   English

HTMLCollection 返回 null

[英]HTMLCollection returning null

I have already looked at other stackoverflow posts and none of them fix my error.我已经查看了其他 stackoverflow 帖子,但没有一个可以解决我的错误。

Trying to get the divs inside the outer div with class name "CodeMirror-code"尝试使用 class 名称“CodeMirror-code”获取外部 div 中的 div

I'm building a chrome extension that directly modifies the html content of a specific webpage and when I call我正在构建一个 chrome 扩展,它直接修改特定网页的 html 内容以及当我调用时

const variable = document.getElementsByClassName('CodeMirror-code');

console.log(variable);

console.log("Length:", variable.length);

the output is: this output 是:这个

Now, when I try to call the first item of HTML collection like现在,当我尝试调用 HTML 集合的第一项时

variable.item(0)

this returns undefined or null这将返回未定义或 null

Other solutions says that you should surround the code in window.onload function in order for the DOM elements to be loaded in. I did this, and there was no change.其他解决方案说您应该将代码包围在 window.onload function 中,以便加载 DOM 元素。我这样做了,没有任何变化。 Is there any way I can fix this error?有什么办法可以解决这个错误吗?

Update: This is what is inside the HTML collection更新:这是 HTML 集合中的内容

Surround your code in a set interval function within window.onLoad and add some delay (like 2000 for 2 seconds).在 window.onLoad 中以设定的间隔 function 包围您的代码,并添加一些延迟(例如 2000 持续 2 秒)。 The only thing that gives HtML collection null is the loading latency of dom elements.唯一给 HtML 集合 null 的是 dom 元素的加载延迟。 If adding delay is still not helping then try to retrace the parents of your div and see till what point your js code is able to catch the expected div.如果添加延迟仍然没有帮助,那么尝试回溯您的 div 的父母,看看您的 js 代码能够捕获预期的 div 直到什么时候。 Then check whether its the problem with load time or scope of the code.然后检查是加载时间问题还是代码的scope问题。

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

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