5

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

Community
  • 1
  • 1
dlchambers
  • 3,511
  • 3
  • 29
  • 34

2 Answers2

6

You can use add() to combine selectors:

var $all = dom.find('.abc').add(dom.filter('.abc'));
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Use .add() to combine selectors.

Add elements to the set of matched elements.

var added = dom.find('.abc').add(dom.filter('.abc'));
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107