Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find does not seem to work

Tags:

jquery

find

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

like image 675
Srikanth Vittal Avatar asked Aug 16 '10 15:08

Srikanth Vittal


3 Answers

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');
  • http://api.jquery.com/filter/

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/

like image 145
user113716 Avatar answered Nov 15 '22 11:11

user113716


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')
like image 2
Yves M. Avatar answered Nov 15 '22 11:11

Yves M.


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.

like image 1
Erik Escobedo Avatar answered Nov 15 '22 12:11

Erik Escobedo