How can I get an element from within a frameset frame using JavaScript?
Asked Answered
M

3

26

I need to access and element from within a frameset frame. For example if I have the following markup:

<frameset rows="33%,33%,*">
  <frame src="frame1.html"/>
  <frame src="frame2.html"/>
  <frame src="frame3.html"/>
</frameset>

How can I get some element from one of the child frames? I have tried this:

window.frames[1].getElementById('someElementId')

This results in a type error :

getElementById() is not a function.

Can someone assist?

Thanks!

Michaelemichaelina answered 24/3, 2010 at 17:26 Comment(0)
C
31

You need to get the Document object for the frame.

window.frames[1].document.getElementById('someElementId')
Consequently answered 24/3, 2010 at 17:30 Comment(0)
O
10
<frameset rows="33%,33%,*">
<frame id="demo" src="frame1.html"/>
<frame src="frame2.html"/>
<frame src="frame3.html"/>
</frameset>

Answer:

document.getElementById("demo").contentDocument.documentElement.innerHTML;
Overlook answered 30/6, 2015 at 0:20 Comment(2)
document.getElementById("demo") returns null !!Vermiculite
@Heitor, my quick guess is that you didn't nest things in document.addEventListener("DOMContentLoaded", function () {/*code here*/});, which might be useful. That said, I get that document.getElementById("demo").contentDocument is null even with the wrapper, though document.getElementById("demo") does return <frame id="demo" src="frame1.html"> using Canary. Weirdness is afoot.Barra
D
9

You can try using framename as well

window.frames['frame_name'].document.getElementsByName('element_name');   
Dicephalous answered 19/6, 2015 at 3:1 Comment(2)
this does not return windows object hence will not work while window.frames[1] return windows object hence works.Cobber
getting frame by name here which is a string i.e frame_name , gave me an error , element implicitly has an 'any' type because index expression is not of type 'number' , had to set suppressImplicitAnyIndexErrors to true in tsconfig.jsonTiffa

© 2022 - 2024 — McMap. All rights reserved.