Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. However, when I do the following it just comes back as null:

document.getElementById('gbx3');

There is a div element in the page that has an id of 'gbx3' - so why is it returning null? What would/could be causing this? The same thing occurs using the Firefox web console.

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.

like image 574
Harry Avatar asked Dec 28 '22 02:12

Harry


2 Answers

GMail is composed of frames. 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):

document.getElementById('hist_frame').contentDocument.getElementById('gbx3');
like image 161
Rob W Avatar answered Dec 29 '22 15:12

Rob W


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

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'));
}
like image 35
Andreas Wong Avatar answered Dec 29 '22 17:12

Andreas Wong