tags:

views:

57

answers:

5

Hi

I have a DocumentFragment stored in "selectedContents", and I am trying to find "span" elements in it, with the help of jQuery. It has two child nodes, where the first one is a text node, and the second one a span.

When I try $(selectedContents.childNodes).find('span'), it returns an empty set!

However, when I print the "$(selectedContents.childNodes)[1].localName" it says "span"!

Is there anything wrong in my find? Please help.

Thanks
Srikanth

+5  A: 

Because you're passing a collection of elements, you need to use .filter() to filter the <span> out of the set.

$(selectedContents.childNodes).filter('span');

The .find() method is used to search for descendants.


EDIT: Note that your approach of passing the childNodes into the jQuery object is correct. You can't pass a documentFragment as some suggest.

Here's an example to illustrate: http://jsfiddle.net/P8nur/

patrick dw
A: 

Try just

$(selectedContents).find('span');
justkt
+2  A: 

With $(selectedContents.childNodes) you already selected all elements from the selectedContents. So doing a find would execute the method on the first element of that selector.

Try this one:

$(selectedContents).find('span')
Yves M.
You'll get unexpected results pasing a `documentFragment` into a jQuery object. (It seems like it should work, but it doesn't.) You need to pass its `childNodes` like OP is doing.
patrick dw
A: 

The thing here is $(selectedContents) return a jQuery magic thing while $(selectedContents.childNodes) return something like an ugly array. So, no find() function for your array.

Use $(selectedContents).find('span') or $(selectedContents.childNodes).filter('span'), as @justkt and @patrick dw said.

Erik Escobedo
Wrong. `$(selectedContents.childNodes)` is also a jQuery object.
SLaks
You can't pass a fragment into a jQuery object. It is, however, supported to pass an array of elements like OP is doing.
patrick dw
A: 

I tried $(selectedContents).find('span'), but it resulted an empty set! As well as the filter, which too resulted empty set!

However $(selectedContents).children('span') resulted what I wanted!

Like patrick_dw said, probably jQuery does not work as expected with DocumentFragment!

Thanks all, for your help.

Srikanth Vittal
Srikanth Vittal - Instead of posting an answer, you should post a comment below someone's answer, or below your question. With regard to your code above, I'd go back to doing `$(selectedContents.childNodes)` since it is fully supported. If jQuery decides to start supporting a fragment as an argument, your code above will break. (And don't forget to click the checkmark next to an answer to "Accept" it.) :o)
patrick dw
Oh! I am pretty new to StackOverflow, next time I will post the comment accordingly.By the way, do you mean I should try the find with $(selectedContents.childNodes)? Like I said in my original post, $(selectedContents.childNodes).find('span') did not work!
Srikanth Vittal