29

So if I have a variable like

var ht = "<body><p>Paragraph Here</p></body>"

If it was attached to the DOM I could just do this to get the text

$('p').text(); 

But can I do the same kind of selection just on a variable that has not yet been attached to the dom?

3 Answers 3

25

The jQuery object will take HTML and make it in to a DOM structure for further query, you can pass it in directly to create the object, or use it as a context if you just wish to query it.

Edit: For some reason it seems necessary to wrap it in a DIV, if not already within one in this example. See the jQuery object documentation on this method for further information.

See test framework for system at: http://jsfiddle.net/hUMqU/

var ht = "<body><p>Paragraph Here</p></body>";
$('<div>' + ht + '</div>').find('p').text();

or as context:

var ht = "<body><p>Paragraph Here</p></body>";
$('p', '<div>' + ht + '</div>').text();
5
  • Thanks, but if I just copy and paste your code above into $(document).ready() neither returns a value. Dec 2, 2010 at 16:03
  • Thanks, but I am still getting no value with both examples even when wrapped in a div Dec 2, 2010 at 16:39
  • Which browser are you using, and what version of jQuery? Remember that the routine creates actual DOM elements, the <body> tag may cause issues. I've tested it in Chrome and Firefox.
    – Orbling
    Dec 2, 2010 at 16:44
  • I am using JQuery 1.4.4 from the Google CDN and Firefox 3.6.1.2 Dec 2, 2010 at 16:54
  • @TooFat Use Firebug or Google Chrome Developer Tools for testing and debugging such snippets interactively. Orbling's code contains a syntax error in the second line. Should be '<div>', not '<div'>.
    – thorn0
    Dec 2, 2010 at 17:02
21

There is no mystery. Selecting

$('p')  

selects p elements of the document, the implied context.

But the p elements in:

var ht = "<body><p>Paragraph Here</p></body>";  

are not attached to the document (DOM) so it's OK if they are not selected.

Fortunately the $() function has a second argument, the context, that has to be used here, like:

$('p', $(ht).context) 
1
  • This needs more upboats
    – Gaspa79
    May 25, 2016 at 18:30
4

Just wrap your HTML String into a jQuery object, and then you can run your jQuery selectors from there:

var htmlString = "<body><p>Paragraph Here</p></body>";
var elements = $(htmlString);

var p = elements.filter('p').text();
console.log(p);
//=> Paragraph Here

Working demo here.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.