1

I want to access page2.html element containing img tag and update it to the page1.html img tag or replace img of page1.html to page2.html img. Both the files are on same domain so no need to worry about cross domain origin policy.

// Page1.html <body> <img id="someimage1" src="./captcha.asp"></img> <iframe src="page2.html"></iframe> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript> var getImg = $('iframe').contents().find('#someimage2').html(); $('#someimage1').replaceWith('<img>' getImg '</img>'); </script> </body> 

I get DOM Update as [object] [Object]

// Page2.html <body> <img id="someimage2" src="./captcha.asp"></img> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> </body> 

2 Answers 2

2

I will help you with one Vanilla JS solution, you can modify it to JQuery:

First check if your IFrame contains any document at all

Firefox and Chrome Solution

var frame = document.getElementById("frame"); if(frame.contentDocument) { // get the inner Document var innerDocument = frame.contentDocument; var img = innerDocument.getElementsByTagName("img")[0]; } 

IE Solution

var frame = document.getElementById("frame"); if(frame.contentDocument) { // get the inner Document var innerDocument = frame.contentWindow.document; var img = innerDocument.getElementsByTagName("img")[0]; } 

When you got the image the rest is just a DOM manipulation operations.

Get Inner Document Body

var getIFrameCOntent = function(iFrame) { var frame = document.querySelector(iFrame); var innerDocument = frame.contentDocument || frame.contentWindow.document; var body = innerDocument.getElementsByTagName("body")[0]; return body; } 

Simple Solution

var frame = document.getElementById('frame').contentWindow.document.body; console.log(frame.getElementsByTagName("img")[0]); 
Sign up to request clarification or add additional context in comments.

1 Comment

contentDocument property doesn't exist in querySelector prototype. Need to hack around: [].forEach.call(document.querySelector(iFrame), function (frame){ var body = innerDocument.getElementsByTagName("body")[0]; });
0

try this code....

page1.html... <html> <head> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> </head> <body> <div id="imgAA"> </div> <img src="img1.jpg" style="width:100px;" id="imgBB"/> <script> $(document).ready(function(){ $("#imgAA").load("page2.html",function(data){ $("#imgBB").attr("src",$("#imgAA").find("img").attr("src")); }); }); </script> </body> 

page2.html... <body> <img src="img2.jpg" style="width:50px;" id="img2"></img> </body> 

try this and tell me it is work fine....

2 Comments

if you don't want to display page2.html content so hidden the div tag
vote up and marked as answer if you got which you want to found

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.