4

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?

2
  • 2
    string s = should be var s =... Commented Jul 22, 2010 at 9:44
  • 1
    +1 just for making us search for fishbiscuits.... Commented Jul 22, 2010 at 9:49

2 Answers 2

6

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();
Sign up to request clarification or add additional context in comments.

5 Comments

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()
@SLC: see my edit, @gnarf: thanks for the correction, when I originally read the question I thought it was already wrapped.
Another Idea: $('<div/>').html(s).find('#fishbiscuits').text();
Another Idea: $(s).siblings('#fishbiscuits').text();
@All: added a bunch of options :-)
3

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

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.