wjdp wjdp - 5 months ago 8
Javascript Question

Parse entire HTML document from string into jQuery

I have a document fetched by a

call, it's a big bloated HTML document. I need to use jQuery to grab an element from it.

I'm trying this (in coffeescript):

$.get url, (data) ->
title = $(data).find('title').text()

This doesn't work. In browser console I've whittled this down to
gives a string of the document.

I've tried jQuery.parseHTML, with the same result.


The reason why it does not work is because jQuery expects a DOM node to find the 'title' tags. As you noted, you need to parse the html text first.

From here and here, the solution is to parse the string and append it into a temporal div (or other element):

var tempDom = $('<div></div>').append($.parseHTML(str));

Then, you can manipulate tempDom to find elements.

Working demo: http://codepen.io/anon/pen/wKwLMP