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?
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?
You need to get the contents of the iFrame first :
$("#myiframe").contents().find('img');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With