skip to Main Content

I’m trying to access a <p> element inside an iFrame through javascript and print it’s contents in the console. However after multiple attempts it always fails to do so.

Here’s the code of the main page:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CS3 - Test Page</title>
    <script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>
</head>

<body>
    <iframe id="frame" src="https://cs3.bluenest.it/Website/test.html"></iframe>

    <script>
        //script to access the iframe and print the contents of the p tag with the id='text'
    </script>
</body>

</html>

And here’s the code of the subpage (test.html) that gets instantiated inside the iframe:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="text"> this text should get printed in the console </p>
</body>
</html>

I’ve tried multiple methods from different sources but they all fail to accomplish my goal:

Method from https://learningjquery.com/2016/09/using-jquery-to-access-iframe-elements

var frame = $("frame").contents();
var element = frame.find("#text");
console.log("content of #text: " + element.html());

The variable element remains undefined and the console prints "content of #text: undefined"


Method from https://www.w3schools.com/howto/howto_js_element_iframe.asp

var frame = document.getElementById("frame");
var element = frame.contentWindow.document.getElementById("text");
console.log("content of #text: " + element.html());

The variable element ends up being null and the console prints out the error "Uncaught TypeError: Cannot read properties of null (reading 'html')"


Method from Selecting an element in iframe with jQuery

var iframe = $('frame');
var element = $('#text', iframe.contents());
console.log("content of #text: " + element.html());

The variable element remains undefined and the console prints "content of #text: undefined"

2

Answers


  1. Could the issue be in the next line:

    var iframe = $('frame');
    

    You’re trying to get iframe but only frame is written.
    Maybe you should try:

        var iframe = $('#frame');
    

    or

        var iframe = $('iframe');
    

    Also, have you checked these answers How to get the body's content of an iframe in Javascript?

    Login or Signup to reply.
  2. Sometimes it’s necessary to check that the iFrame content has loaded.

    $(function () {
      $('iframe').on('load', function () {
        const para = $(this).contents().find('p');
        console.log($(para).text());
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search