简体   繁体   中英

jquery attr() method doesn't work but javascript version does

Here is my current javascript code

var image = iframe.contentWindow.document.getElementsByClassName('productVisu').getElementsByTagName('img').getAttribute('src');

This works in retrieving the URL attribute of an image. However when I try this jquery version:

var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var image = $('iframe').contents().find('.productVisu').$('img').attr('src');

I get the firefox error that this not a function. How do I resolve this issue and get the jquery version working?

Thanks

Change this:

$('iframe').contents().find('.productVisu').$('img').attr('src');

to:

$('iframe').contents().find('.productVisu img').attr('src');

I'm not sure how your original code works, since getElementsByClassName and getElementsByTagName return node lists, not individual nodes.

Try this instead:

var image = iframe.contentDocument.querySelector(".productVisu img").src;

Never use jQuery when you can use Vanilla JS . It's like turning a screw with a sledgehammer.

I don't understand the need for the first two lines of code in your example. You could easily do this:

var image = $('iframe').eq(0).find('.productVisu img').attr('src');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM