164

I have a big HTML-string containing multiple child-nodes.

Is it possible to construct a jQuery DOM object using this string?

I've tried $(string) but it only returns an array containing all the individual nodes.

Imtrying to get an element which i can use the .find() function on.

user1033619
  • 1,757
  • 2
  • 11
  • 11

8 Answers8

239

Update:

From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:

var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));

alert( dom_nodes.find('input').val() );

DEMO


var string = '<div><input type="text" value="val" /></div>';

$('<div/>').html(string).contents();

DEMO

What's happening in this code:

  • $('<div/>') is a fake <div> that does not exist in the DOM
  • $('<div/>').html(string) appends string within that fake <div> as children
  • .contents() retrieves the children of that fake <div> as a jQuery object

If you want to make .find() work then try this:

var string = '<div><input type="text" value="val" /></div>',
    object = $('<div/>').html(string).contents();

alert( object.find('input').val() );

DEMO

Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
126

As of jQuery 1.8 you can just use parseHtml to create your jQuery object:

var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));

I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/

It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.

Daniel Sokolowski
  • 11,982
  • 4
  • 69
  • 55
kiprainey
  • 3,241
  • 4
  • 29
  • 29
  • 10
    I find this answer far better, since this don't have to use a ghost div element. $.parseHtml ftw. – ZeeCoder Aug 28 '13 at 14:14
  • 3
    This answer didn't work for me when I wanted then then to $jQueryObject.find(), I presume because it wasn't added to the dom at that point. – dougajmcdonald Oct 29 '13 at 18:02
  • @dougajmcdonald -- find should work without the content being added to the dom. If you take a look at my fiddle (http://jsfiddle.net/MCSyr/2/), I'm calling find on the jQuery object, and it returns a result as expected: $jQueryObject.find("#theAnswer").html() – kiprainey Nov 18 '13 at 22:55
  • 1
    @kiprainey interesting, I'll dig out the example it didn't for me on and see if there was something else afoot. It was written inside a TypeScript module inside a load of other logic, could well have been a different issue! My apologies. – dougajmcdonald Nov 19 '13 at 09:16
  • 8
    Worth mentioning that parseHTML was added in **jQuery 1.8** – Jean-Michel Garcia Dec 27 '13 at 17:32
  • This still breaks for certain queries unless you wrap it in a ghost div. Changing the above example: http://jsfiddle.net/ykwd8d01/ - but works if you wrap it in a ghost div: http://jsfiddle.net/g9d81y1x/ – Nathan Fig Jan 01 '17 at 17:42
  • I had to use filter not find on $jQueryObject – Matthew Lock Mar 14 '18 at 07:44
  • This will also yeild the same result `$(string).find("#theAnswer").html()` http://jsfiddle.net/cxf57ha4/ – Andy Gee Nov 22 '18 at 11:10
  • @kiprainey what if I want to extract the HTML after performing operations like `remove()`? When I do `jQueryObject.html()` it does not return HTML at all – Volatil3 Jun 23 '22 at 15:08
13
var jQueryObject = $('<div></div>').html( string ).children();

This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
2

There is also a great library called cheerio designed specifically for this.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

var cheerio = require('cheerio'),
    $ = cheerio.load('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html();
//=> <h2 class="title welcome">Hello there!</h2>
Loourr
  • 4,995
  • 10
  • 44
  • 68
2

I use the following for my HTML templates:

$(".main").empty();

var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");

$(".main").append(final.html());

Note: Assuming if you are using jQuery

Anthony
  • 31
  • 1
1

the reason why $(string) is not working is because jquery is not finding html content between $(). Therefore you need to first parse it to html. once you have a variable in which you have parsed the html. you can then use $(string) and use all functions available on the object

Chetan
  • 4,735
  • 8
  • 48
  • 57
0

You can try something like below

$($.parseHTML(<<table html string variable here>>)).find("td:contains('<<some text to find>>')").first().prev().text();
Chirag
  • 1,478
  • 16
  • 20
0

I know this is an old thread, but I have another simple answer. jQuery has moved up quite a few versions and I'm on 1.13.x

Not being an expert jQuery programmer, I näively used:

var el = $( "#thecontainer" ).append( "<legit, lengthy html>" );

And presto! It worked: el is now a fully operational jQuery dom element.

I have been testing it out over the past couple of days and it seems to work as expected.

horace
  • 938
  • 9
  • 20