Selecting an element in iframe with jQuery

JavascriptIframeGetelementbyid

Javascript Problem Overview


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 token IDs. I need to select the elements by those token IDs. 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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

https://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe

Solution 3 - Javascript

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();
    });
});

Solution 4 - Javascript

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

Solution 5 - Javascript

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

$("#containerdiv div").draggable( {containment: "#containerdiv ", scroll: false} );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncyceroView Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - JavascriptKevin BowersoxView Answer on Stackoverflow
Solution 3 - JavascriptFareed AlnamroutiView Answer on Stackoverflow
Solution 4 - JavascripttiberskyView Answer on Stackoverflow
Solution 5 - JavascriptRajasekharreddy KadasaniView Answer on Stackoverflow