tags:

views:

36

answers:

2

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?

+6  A: 

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();
Andy E
This does not work for me.
SLC
although since `#fishbiscuits` is at the "root" of that document, you'll need to `.filter()` instead of `.find()`, or wrap `s` up in another element like: `$('<div>'+s+'</div>').find("#fishbiscuits").text()`
gnarf
@SLC: see my edit, @gnarf: thanks for the correction, when I originally read the question I thought it was already wrapped.
Andy E
Another Idea: `$('<div/>').html(s).find('#fishbiscuits').text();`
gnarf
Another Idea: `$(s).siblings('#fishbiscuits').text();`
jAndy
@All: added a bunch of options :-)
Andy E
+3  A: 

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

Jan Hančič
why the downvote?
Jan Hančič
No clue, solid solution... other than the missing `$` on the third line :)... Also, personally I think `dummyElement.find('#fishbiscuits')` is a little easier to read than `$('#fishbiscuits',dummyElement)`
gnarf
oops, missed the missing $, thanks!
Jan Hančič
+1 from me to even it out a little.
Andy E