Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I get the text of a particular element from an external domain webpage?
Example: Get the text inside the element <h1 class='lawtitle'> from the webpage "https://thecorpusjuris.com/legislative/republic-acts/ra-no-11460.php"?
I actually want to create a webpage that displays a list (number and title) of Republic Acts in descending order from No. 11460 down to No. 1.


What I have tried:

<div id='myList'>List of Republic Acts</div>
<iframe src='https://thecorpusjuris.com/legislative/republic-acts/ra-no-11460.php' width='100%' height='600px'></iframe>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {

        for (var i = 11460; i > 11450; i--) {

            $("iframe").src = "https://thecorpusjuris.com/legislative/republic-acts/ra-no-" + i + ".php";

            var lawtitle = $("h1.lawtitle").html(); // this line returns 'undefined'. Please write here the codes to get the text inside the element <h1 class='lawtitle'> from the above-mentioned external domain webpage

            $("#myList").append("<p>R.A. " + i + " - " + lawtitle + "</p>");

        }

    });
</script>
Posted
Updated 26-Sep-22 4:15am
v2

1 solution

Not sure why this question has come back to the top of the list. Assuming someone is still after an answer:

You can't. Unless the remote site specifically sends CORS headers[^] to indicate that your site is allowed to access its data, cross-domain requests are blocked for security reasons.

Your only option is to create a server-side proxy endpoint. The Javascript on your site calls a server-side script hosted on your site, which loads the page from the remote site on your server and returns the relevant data to your Javascript.

How you do that will depend on which server-side language you are using, which wasn't part of your question.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900