Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick element inside iframe using document.getElementById

I have a iframe like this

<iframe name="myframe1" id="myframe1" width="100%" height="100%" src="a.html"> <html>     <head></head>     <frameset name="myframe2" cols="0%, 100%" border="0" frameBorder="0" frameSpacing="0">         <frame name="page1" src="c.html" scrolling="no"></frame>         <frame name="page2" src="d.html" >             <html>                 <head></head>                 <body id="top">                     <div id="div1">                         <div id="div2">                             <div id="div3">                                 <ul id="x">                                     <li>a</li>                                     <li>b</li>                                 </ul>                             </div>                         </div>                     </div>                 </body>             </html>          </frame>      </frameset> </html> </iframe> 

I want to refer to the element "x". I tried in several ways but I couldn't find a solution.

like image 578
ishk Avatar asked Jan 22 '13 03:01

ishk


People also ask

How do I select an element in an iframe?

Getting the element in Iframeconst iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe. const iWindow = iframe.

Can JavaScript access iframe content?

You could use . contents() method of jQuery. The . contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.


1 Answers

document.getElementById('myframe1').contentWindow.document.getElementById('x') 

Fiddle

contentWindow is supported by all browsers including the older versions of IE.

Note that if the iframe's src is from another domain, you won't be able to access its content due to the Same Origin Policy.

like image 126
Fabrício Matté Avatar answered Sep 25 '22 14:09

Fabrício Matté