admin管理员组

文章数量:1201353

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?

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?

Share Improve this question edited May 10, 2011 at 14:59 kapa 78.7k21 gold badges164 silver badges177 bronze badges asked May 10, 2011 at 14:52 jakejake 1,9393 gold badges23 silver badges31 bronze badges 1
  • 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 Commented May 10, 2011 at 14:57
Add a comment  | 

5 Answers 5

Reset to default 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();

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

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.

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

Yes. And even if that is not available you could make an invisible div and then parse it there.

本文标签: javascriptCan jQuery Parse HTML Stored in a VariableStack Overflow