Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get jquery objects from an html string thats not in the DOM?

For example in javascript code running on the page we have something like:

var data = '<html>\n  <body>\n  I want this text ...\n  </body>\n</html>';

I'd like to use and at least know if its possible to get the text in the body of that html string without throwing the whole html string into the DOM and selecting from there.

like image 822
Travis Avatar asked Feb 04 '23 03:02

Travis


1 Answers

First, it's a string:

var arbitrary = '<html><body>\nSomething<p>This</p>...</body></html>';

Now jQuery turns it into an unattached DOM fragment, applying its internal .clean() method to strip away things like the extra <html>, <body>, etc.

var $frag = $( arbitrary );

You can manipulate this with jQuery functions, even if it's still a fragment:

alert( $frag.filter('p').get() ); // says "<p>This</p>"

Or of course just get the text content as in your question:

alert( $frag.text() ); // includes "This" in my contrived example
                       // along with line breaks and other text, etc

You can also later attach the fragment to the DOM:

$('div#something_real').append( $frag );

Where possible, it's often a good strategy to do complicated manipulation on fragments while they're unattached, and then slip them into the "real" page when you're done.

like image 165
Ken Redler Avatar answered Feb 05 '23 17:02

Ken Redler