I'm using PHP and an ajax command to take the entire HTML contents of an external web page (via the PHP file_get_contents()
command) and passing that HTML into a javascript variable. Once I have the page's HTML contents stored in a variable, can I use jQuery to interact with the contents of that variable, in the same way that jQuery normally interacts with the DOM? In this example, I am trying to search for the existence of certain HTML elements (<div>
and <script>
tags) with specific ID attributes. Can anyone suggest how I can accomplish this?
Asked
Active
Viewed 1.3k times
5
-
Just to clarify, I want to use jQuery to extract data *from* the variable that contains the HTML contents of the external web page. – jake May 10 '11 at 14:57
5 Answers
15
If I understand you correctly, you should be able to just pass the variable to the jQuery function and work accordingly.
A quick example with .filter()
:
$(myHtml).filter('#someid').doStuff();

BoltClock
- 700,868
- 160
- 1,392
- 1,356
6
Just pass it as a string to the jQuery constructor.
var foo = jQuery('<p><b>asd</b><i>test</i></p>').
alert(foo.find('i').text());

Quentin
- 914,110
- 126
- 1,211
- 1,335
1
You can even use native JS to do this. In this case, add the new HTML to a hidden div by using its innerHTML property like this:
document.getElementById('hidden_div_id').innerHTML = myHTML;
Once the new HTML is added, you can walk through nodes using whatever methods you want.

KJ Saxena
- 21,452
- 24
- 81
- 109
0
Just inject it into a hidden div and manipulate what you need from it in there.
var myHTML;//variable with html from php
var $hiddenDIV = $('<div></div>').hide().appendTo('body').html(myHTML);
/*Now you can traverse the contents of $hiddenDIV.
* If you need to get the contents back:
*/
var newHTML = $hiddenDIV.html();

Mechlar
- 4,946
- 12
- 58
- 83
-
If I did this, how would I prevent the javascript from the external web page's HTML from running? – jake May 10 '11 at 15:08
-
Well, you could remove the javascript from the the html and store it in another variable, or if you don't need the javascript at all for your purposes then you could just remove it altogether. Let me know if you need help writing that script. – Mechlar May 10 '11 at 15:10
-
@jake - however, this approach might be an overkill. I would use BoltClock's approach. – Mechlar May 10 '11 at 15:18