4

I'm trying to figure out how to select, and then modify, the HTML within an iframe I generate. The iframe displays various media (images, pdfs, etc.). To show different items, I initially create it using something like this:

$('#mydiv').html("<iframe id='myiframe' src='path/file.jpg'></iframe>");

and then, as needed, update its contents using something like this:

$('#myiframe').attr("src","path/newfile.jpg");

this produces HTML like this (as seen through Chrome's elements viewer):

<div id='mydiv'>
  <iframe id='myiframe' src='path/file.jpg'>
    #document
      <html>
        <body style="margin:0">
          <img style="-webkit-user-select:none" src="path/file.jpg">
        </body>
      </html>
  </iframe>
</div>

I want to select that dynamically generated <img> tag so that I can adjust its width. But I can't figure out the jquery selector to do it. Ideas?

6
  • 1
    is there a reason the jpg is being included in an iframe and not in an img/div with background-image? Commented May 21, 2012 at 19:53
  • why an iframe for image and not img ? Commented May 21, 2012 at 19:53
  • The iframe displays various media (images, pdfs, etc.) Commented May 21, 2012 at 19:54
  • blender has it. sometimes the iframe shows an onsite or offsite PDF, for example. Commented May 21, 2012 at 19:55
  • 1
    see like question--> stackoverflow.com/questions/1088544/… Commented May 21, 2012 at 19:56

3 Answers 3

13

Use jQuerys contents method. The docs even has an example titled "Change the background colour of links inside of an iframe."

Get the children of each element in the set of matched elements, including text and comment nodes.

Applied to your code:

var images = $('#myiframe').contents().find('img');

The real question is why do you need the iframe in the first place?

Sign up to request clarification or add additional context in comments.

1 Comment

Correct answer, +1. And you where a few seconds faster then me!
4

You need to get the contents of the iFrame first :

$("#myiframe").contents().find('img');

Comments

0

If all you want to do is dynamically change an image in a container, you don't need the iframe.

You just need a an img tag on your own html that you can update it's src attribute.

$('#my-image')
    .attr('src', '/path/to/image')
    .attr('width', '100px')
    .attr('height', '100px');

unless you haven't told us a good reason to generate an iframe just for an image. Playing with iframes like that can be painful specially when calling URLs from other domains

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.