jQuery() not finding elements in jQuery.parseHTML() result

Just ran into this.

Turns out $.parseHTML returns a vanilla Array of DOM elements, and that doesn't support the jQuery find that you want.

I think this is the cleanest solution for converting an HTML string to a jQuery object:

var html = '<div><span id="foo">hello</span></div>';
var $foo = $(html).find('#foo');

Note: You may want to use $.trim around your html strings so jQuery doesn't get confused by whitespaces.


You need to create a DOM element to append the results of .parseHTML() first so that it creates a DOM tree before jQuery can traverse it and find div#app-container.

var tempDom = $('<output>').append($.parseHTML(str));
var appContainer = $('#app-container', tempDom);

I used your example and got it working: http://jsfiddle.net/gEYgZ/

The .parseHTML() function seems to choke on the <script> tags, so I had to remove them.

PS. Obviously <output> is not a real HTML tag, just using it for the example


You can try this:

$($.parseHTML('<div><span id="foo">hello</span></div>')).find('#foo');

for strings that start with < you can shorter that code to just:

$('<div><span id="foo">hello</span></div>').find('#foo');