1

I have an iframe. I want to access a table which present inside iframe.I want to access it from parent window of iframe. I have written JS like

Document.getElementById("table Id");

But the result come null. What is the process to get it? thanks

user1122379
  • 19
  • 1
  • 2
  • 4

2 Answers2

4

x=document.getElementById("iFrameId");
x.contentDocument.getElementById("tableId");

if you can use jQuery i guess it will work across browsers

$("#iFrameId").contents().find("#tableId")

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
  • Thanks. But it is not working. Now I am thinking that I can use a div and fill that div using PHP httprequest to the url. But I dont know how to do that httpRequest. Could you provide me some example code please? – user1122379 Dec 30 '11 at 06:43
1

You have to select the element from the iFrame's document. Per Juan's comment, check against both the name, and id of the iFrame

var targetFrame = window.frames["nameOfIFrame"] || window.frames["iFrameId"];
targetFrame.document.getElementById("tableId");

EDIT

I just tested this with the following:

window.frames["fName"].document.getElementById("Adam").innerHTML

in the Chrome console, and it output the html of the Adam div from within my iframe.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • What's wrong with it? `window.frames["iFrameId"].document.getElementById` seems to come back as a native method – Adam Rackis Dec 30 '11 at 05:47
  • http://stackoverflow.com/questions/729577/can-javascript-access-iframe-elements-from-the-parent-page – Pencho Ilchev Dec 30 '11 at 05:53
  • @PenchoIlchev - that question deals with an iframe loading code on a **different domain** - OP never said that was the case here. Assuming the iFrame is loading the same domain, the above code seems to work fine -- I just tested it – Adam Rackis Dec 30 '11 at 05:54
  • `frames[frameName]` is the best cross browser way to access the window object inside frames. Your example implies an ID but my experience is the you should also use the name attribute. http://stackoverflow.com/questions/1644676/javascript-accessing-frameset-frames-from-within-other-frames – Ruan Mendes Dec 30 '11 at 06:30
  • @JuanMendes - Thanks. I tested it and using the name of the iFrame works splendidly. I didn't know that was preferable to using an id, but I edited my answer. – Adam Rackis Dec 30 '11 at 06:56
  • @AdamRackis: You should use both `id` and `name` in the HTML for complete cross-browser goodness! At least that was true around three years ago with IE 7, chrome and firefox – Ruan Mendes Dec 30 '11 at 16:55