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.
console.log($(page).map(function () {
return this.nodeName;
}).toArray());
// ["H1", "P", "SPAN", "P"]
html()
returns the innerHTML
of the first element in this jQuery object; which is why you only see "Hello!".
To find the .username
you should use the filter()
method, which searches within the jQuery object for elements which match the given selector.
alert($(page).filter('.username').text()); // "this is ur name", kthx.
See your updated fiddle here; http://jsfiddle.net/6TSuq/15/
Bare in mind that in future, you might have nested elements such as this;
var page = "<h1><span class='username'>Foo</span></h1>";
In this circumstance, filter()
ing for .username
will yeild no results; as the jQuery object $(page)
does not contain the .username
element; it contains a h1
, which has a descendant which is a .username
. Therefore here you'd need to use;
alert($(page).find('.username').text());
For reference, see find()
, filter()
and map()