I have some HTML stored in a string which I parse using jQuery. The HTML is something like:
<div class='person'>
<span class='name'>Joey</span>
<img class='avatar' src='...'/>
</div>
<div class='person'>
<span class='name'>Dee Dee</span>
<img class='avatar' src='...'/>
</div>
<div class='person'>
<span class='name'>Tommy</span>
<img class='avatar' src='...'/>
</div>
<div class='person'>
<span class='name'>Johnny</span>
<img class='avatar' src='...'/>
</div>
So I use jQuery to parse the HTML like this (suppose the HTML is stored in the variable ‘data’):
$(".name", data) returns all the .name elements
$(".avatar", data) returns all the .avatar elements
BUT $(".person", data) returns and empty object.
So apparently jQuery cant parse the top level elements. Why is this? What is the best way to get around it?
Of course I can always insert ‘data’ inside a dummy element and then parse it, but that doesn´t seem a very elegant solution to me…
From the docs –
and then from the ‘find‘ docs –
So the
$(".person", data)selector will always return an empty result set (as it contains no `.person’ descendants) unless you wrap it in a dummy object before searching.