[jQuery Tip] Traverse/Parse HTML String

| 1 min read

When you are getting an HTML string from an external source (e.g. from an AJAX get result) and you want to rip out a certain part of the HTML source, you need to make sure that the ‘certain part’ is not at the top level of the HTML source.

For example, we have the following HTML string:


If we want to get the first paragraph element by using:

// data is the HTML source
$('span#first', data)

The above code won’t work, because the p tags are at the top level. Instead, we can simply wrap the HTML source with a div tag and that’ll do it. :)

Enjoy what you are reading? Sign up for a better experience on Persumi.