jQuery find does not seem to work

后端 未结 5 704
南方客
南方客 2020-12-19 10:32

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 o

相关标签:
5条回答
  • 2020-12-19 10:58

    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')
    
    0 讨论(0)
  • 2020-12-19 11:02

    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.

    0 讨论(0)
  • 2020-12-19 11:06

    Try just

    $(selectedContents).find('span');
    
    0 讨论(0)
  • 2020-12-19 11:06

    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.

    0 讨论(0)
  • 2020-12-19 11:12

    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/

    0 讨论(0)
提交回复
热议问题