NibblyPig
NibblyPig

Reputation: 52922

Parse a string containing html using 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?

Upvotes: 4

Views: 603

Answers (2)

Andy E
Andy E

Reputation: 344507

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

Upvotes: 6

Jan Hančič
Jan Hančič

Reputation: 53930

Based on the info provided, this should do the trick:

var s = "<p>Cats</p><div id='fishbiscuits'>myValue</div>";
var dummyElement = $( '<div>' + s + '</div>' );
var yourString = $( '#fishbiscuits', dummyElement ).html ();

It basicly creats a new DOM element containing the HTML in your string, then searches for the element with the id 'fishbiscuits' and returns it's inner HTML

Upvotes: 3

Related Questions