jQuery – Select an HTML Element inside an iFrame

This post shows you how to select an HTML Element inside an iframe using jQuery. The code looks in this way.

var iframe = $('#your-iframe');
iframe.on('load', function() {
    var iframeContents = $(this).contents();
    var element = iframeContents.find('selector');
})

Here an example showing how it works. First, create a simple sub-page.html, that will be displayed inside a iframe.

sub-page.html
<!DOCTYPE html>
<html>
<head>
    <title>Sub Page</title>
</head>
<body>
    <div id="message">This is sub page</div>
</body>
</html>

This sub-page.html page contains a div#message element, which we will try to get it later in jQuery code.

Then, create a parent-page.html with the following content. Click on the “Run Example” button to see how it works.

parent-page.htmlRun Example
<!DOCTYPE html>
<html>
<head>
    <title>jQuery – Select an HTML Element inside an iFrame</title>
</head>
<body>
    <h4>iFrame:</h4>
    <iframe id="iframe1" src="https://bytenota.com/demos/demo-files/iframes/sub-page.html"></iframe>
	
    
    <h4>Content in iFrame:</h4>
    <div id="iframe-content"></div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        
        $(function() {
            var iframe = $('#iframe1');
            iframe.on('load', function() {
                // iframe content
                var iframeContents = $(this).contents();

                // find #message in iframe contents
                var element = iframeContents.find('#message');

                // get element value
                var message = element.html();

                // display element value in view
                $('#iframe-content').html(message);
            })
        });

    </script>

</body>
</html>

Please note: We can’t access iframe with different origin because of security issue.