开发者

Can jQuery Parse HTML Stored in a Variable?

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 existenc开发者_运维百科e of certain HTML elements (<div> and <script> tags) with specific ID attributes. Can anyone suggest how I can accomplish this?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜