Selecting an element in iFrame jQuery

2019-01-04 00:38发布

In our application, we parse a web page and load it into another page in an iFrame. All the elements in that loaded page have their tokenid-s. I need to select the elements by those tokenid-s. Means - I click on an element on the main page and select corresponding element in the page in the iFrame. With the help of jQuery I'm doing it in the following way:

function selectElement(token) {
     $('[tokenid=' + token + ']').addClass('border'); 
}

However with this function I can select the elements in the current page only, not in the iFrame. Could anybody tell me how can I select the elements in the loaded iFrame?

Thanks.

5条回答
你好瞎i
2楼-- · 2019-01-04 01:00

If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).

Chrome Dev Tools - Selecting the iFrame

查看更多
看我几分像从前
3楼-- · 2019-01-04 01:01

Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html

$("#iframeID").contents().find("[tokenid=" + token + "]").html();

Place your selector in the find method.

This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.

jQuery/JavaScript: accessing contents of an iframe

查看更多
Emotional °昔
4楼-- · 2019-01-04 01:02

here is simple JQuery to do this to make div draggable with in only container :

$("#containerdiv div").draggable( {containment: "#containerdiv ", scroll: false} );
查看更多
Rolldiameter
5楼-- · 2019-01-04 01:03
var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');

Also note that if the src of this iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.

查看更多
Root(大扎)
6楼-- · 2019-01-04 01:19

when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:

$(function() {
    $("#my-iframe").bind("load",function(){
        $(this).contents().find("[tokenid=" + token + "]").html();
    });
});
查看更多
登录 后发表回答