简体   繁体   English

对于已知元素,document.getElementById返回null - 为什么?

[英]document.getElementById coming back with null for a known element - why?

I'm using the Google Chrome JavaScript console and I was just looking at the Gmail page and just practicing manipulating the DOM. 我正在使用Google Chrome JavaScript控制台,我只是在查看Gmail页面,只是练习操作DOM。 However, when I do the following it just comes back as null: 但是,当我执行以下操作时,它只会返回null:

document.getElementById('gbx3');

There is a div element in the page that has an id of 'gbx3' - so why is it returning null? 页面中有一个div元素,其id为'gbx3' - 为什么它返回null? What would/could be causing this? 会导致什么/可能导致这种情况? The same thing occurs using the Firefox web console. 使用Firefox Web控制台也会发生同样的事情。

If you try and access the 'gb' id (this is the main top toolbar) in the same Gmail page it comes back null, but if you access this element at google.com it will come back with the element. 如果您尝试访问同一个Gmail页面中的'gb' ID(这是主要顶部工具栏),则会返回null,但如果您在google.com上访问此元素,则会返回该元素。

GMail is composed of frames. GMail由框架组成。 This one works: 这个工作:

frames[3].document.getElementById('gbx3');

In general, if you know the ID of the iframe element, the contentDocument property can be used (provided that you don't have same-origin problems, and the document is loaded): 通常,如果您知道iframe元素的ID,则可以使用contentDocument属性(假设您没有同源问题,并且文档已加载):

document.getElementById('hist_frame').contentDocument.getElementById('gbx3');

As per my comment: 根据我的评论:

My best bet is that gbx is inside the iframe that contained the search result, and document.getElementById works on the same scope as your console 我最好的选择是gbx位于包含搜索结果的iframe内,而document.getElementById与控制台在同一范围内工作

You can search all the frames to find what you need: 您可以搜索所有帧以查找所需内容:

for(var i = 0; i < frames.length; i++) {
   var curDoc = frames[i].document;
   if(curDoc.getElementById('gbx')) console.log(curDoc.getElementById('gbx'));
}

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

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