Can jQuery Parse HTML be stored in a variable?

I use PHP and the ajax command to get all the HTML content of an external web page (using the PHP file_get_contents() command) and pass that HTML to a javascript variable. Once I store the contents of the HTML page of a page in a variable, can I use jQuery to interact with the contents of this variable in the same way that JQuery normally interacts with the DOM? In this example, I am trying to find the existence of certain HTML elements ( <div> and <script> ) with specific identifier attributes. Can anyone suggest how I can do this?

+4
source share
5 answers

If you understand correctly, you should just pass the variable to the jQuery function and work accordingly.

Quick example with .filter() :

 $(myHtml).filter('#someid').doStuff(); 
+12
source

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()); 
+4
source

You can even use native JS for this. In this case, add the new HTML to the hidden div using its innerHTML property as follows:

 document.getElementById('hidden_div_id').innerHTML = myHTML; 

After adding new HTML, you can go through the nodes using whatever methods you want.

+1
source

Yes. And even if this is not possible, you can make an invisible div and then parse it there.

0
source

Just enter it into a hidden div and control what you need from it 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(); 
0
source

All Articles