Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine results of jQuery find() and filter()? [duplicate]

Say I composed a DOM snippet:

var dom = $("
    <div id='root' class='abc'>
       <div id='child1' class='xxx'>no-match</div>
       <div id='child2' class='abc'>match!</div>
       <div id='child3' class='xxx'>no-match</div>
    </div>
");

and I want to retrieve all elements with '.abc' (i.e. #root and #child2)

dom.find('.abc') will return all matching child elements (ie. just #child2)
dom.filter('.abc') will return all matching root elements (ie. just #root)

How can I either:
- Make one call that finds both #root and #child2, or
- Combine the results of find() and filter()

I've seen other posts on "combining" results eg: How to combine two jQuery results but that's not really "combining" but rather "appending more results to a pre-existing result"

What I really want to do is something akin to $.extend():

var one = dom.find('.abc');
var two = dom.filter('.abc');
var three = combine(one, two);
// or one.somefcn(two); // One is augmented
// or three = one.somefcn(two); // 

Any info/ideas would be appreciated

like image 743
dlchambers Avatar asked Oct 14 '13 14:10

dlchambers


2 Answers

You can use add() to combine selectors:

var $all = dom.find('.abc').add(dom.filter('.abc'));
like image 170
Rory McCrossan Avatar answered Nov 15 '22 12:11

Rory McCrossan


Use .add() to combine selectors.

Add elements to the set of matched elements.

var added = dom.find('.abc').add(dom.filter('.abc'));
like image 37
Tushar Gupta - curioustushar Avatar answered Nov 15 '22 13:11

Tushar Gupta - curioustushar