Creating a jQuery object from a big HTML-string

html, javascript, jquery

Solution

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

Problem

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.

Original source

Related problems