Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a string containing html using JQuery

Tags:

html

jquery

Astounded this question didn't show up in the related questions list. There's some similar stuff, but I'd like to know:

string s = "<p>Cats</p><div id='fishbiscuits'>myValue</div>";

I want to use JQuery to get myValue.

How can I do this?

like image 657
NibblyPig Avatar asked Jan 22 '23 17:01

NibblyPig


1 Answers

Use the jQuery function to create the objects and then you can use it like you would any other collection of elements. Any of these should work just fine:

// Using filter()
$(s).filter("#fishbiscuits").text();

// Wrapping with a div and using find()
$('<div>' + s + '</div>').find("#fishbiscuits").text();

// Wrapping with a div and using selector context
$('#fishbiscuits', '<div>' + s + '</div>').text();

// Creating a div, setting the html and then using find
$('<div>').html(s).find("#fishbiscuits").text();
like image 145
Andy E Avatar answered Feb 01 '23 21:02

Andy E