1

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

http://jsfiddle.net/6TSuq/1/

4

2 回答 2

5

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()

于 2012-09-05T15:19:07.407 回答
1

A very simple way to do this is:

var elem = $('<h1>Hello!</h1><p>FOO</p><span class="username">this is ur name</span><p>sample text</p>').filter('.username').get(0);
console.log($(elem).html()); // returns this is ur name

​jsFiddle example

You need to convert your string to a jQuery object first in order to use any jQuery method on it.

于 2012-09-05T15:28:34.180 回答