I have the following Code
var page = '<h1>Hello!</h1><p>FOO</p><span class="username">this is ur name</span><p>sample text</p>';
when I alert $(page).html() i get Hello! and when I wrap the contents of the page in a div and alert $(page).html() I get the whole html contents.
What I am trying to accomplish here is I have a page string with html template and I am trying to find a class username in it and i am getting null.
I am confused with this happens
Here is a small fiddle of the issue
When you call
$(page)you construct a jQuery object which contains 4 elements; for each of the HTMLElements that aren’t nested in your string.
html()returns theinnerHTMLof the first element in this jQuery object; which is why you only see “Hello!”.To find the
.usernameyou should use thefilter()method, which searches within the jQuery object for elements which match the given selector.See your updated fiddle here; http://jsfiddle.net/6TSuq/15/
Bare in mind that in future, you might have nested elements such as this;
In this circumstance,
filter()ing for.usernamewill yeild no results; as the jQuery object$(page)does not contain the.usernameelement; it contains ah1, which has a descendant which is a.username. Therefore here you’d need to use;For reference, see
find(),filter()andmap()