Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select tags within an iframe using jquery?

Tags:

jquery

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?

like image 337
mix Avatar asked Dec 03 '22 03:12

mix


2 Answers

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?

like image 92
Seth Flowers Avatar answered Jan 07 '23 10:01

Seth Flowers


You need to get the contents of the iFrame first :

$("#myiframe").contents().find('img');
like image 22
adeneo Avatar answered Jan 07 '23 11:01

adeneo