How to select tags in iframe using jquery?

I am trying to figure out how to select and then change the HTML in the iframe that I am generating. IFrame displays various media (images, PDF files, etc.). To show the different elements, I first create them using something like this:

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

and then, if necessary, update its contents using something like this:

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

this creates HTML like this (as seen through viewing the elements of Chrome):

 <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 a dynamically generated <img> tag so that I can adjust its width. But I cannot define a jquery selector to do this. Ideas?

+4
source share
3 answers

Use the jQuerys contents method. Documents even have an example called "Change the background color of links inside an iframe."

Get the children of each element in the set of matched elements, including text and node comments.

Applies to your code:

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

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

+12
source

First you should get the contents of the iFrame:

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

If all you want to do is dynamically change the image in the container, you do not need an iframe.

You just need the img tag on your own html, which you can update the src attribute.

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

if you didn’t tell us the reason for generating an iframe for the image only. Playing with such iframes can be painful especially when calling URLs from other domains

0
source

Source: https://habr.com/ru/post/1413604/


All Articles