how to select tags within an iframe using jquery?

2020-07-18 07:21发布

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?

标签: jquery
3条回答
Summer. ? 凉城
2楼-- · 2020-07-18 08:04

You need to get the contents of the iFrame first :

$("#myiframe").contents().find('img');
查看更多
再贱就再见
3楼-- · 2020-07-18 08:15

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

查看更多
虎瘦雄心在
4楼-- · 2020-07-18 08:26

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?

查看更多
登录 后发表回答