Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include context elements in search space when using jQuery( selector [, context ] )

Tags:

jquery

I have an existing collection of elements that I want to change if they match a given selector. I want to do the same to these items' descendants (recursively). This seems like the function of jQuery( selector [, context ] ). However, the resulting set does not include the parent elements. I want to query them too. Can this be done with one command?

for example,

var els = $('<div foo="bar">')
$("[foo]", els ); // finds nothing
els.filter("[foo]"); // finds div 

But filter does not search descendants, so

var els = $('<div foo="bar"><span foo="foobar"></div>')
$("[foo]", els ); // finds span
els.filter("[foo]"); // finds div

What's the best way to find both the span and the div? Use both commands? Is there a single line command to find both? Better than this anyway?

var els = $('<div foo="bar"><span foo="foobar"></div>')
var selection = $("[foo]", els ); // finds inner elements
selection = selection.add(els.filter("[foo]")); // then adds on parents that match the selector
like image 200
AlexMA Avatar asked Nov 02 '22 22:11

AlexMA


1 Answers

The context is for supplying an element or collection of elements to look within, meaning the descendants of those elements. It does not filter like .filter does, it's more like .find.

If you want both, you'll have to use both:

$("[foo]", els ).add( els.filter("[foo]") );

or use a parent element.

$("[foo]", $("<div>").html(els) );

so, no there isn't a better way.

The second method is how jQuery's .load method does it, but i wouldn't consider it any better.

https://github.com/jquery/jquery/blob/1.9-stable/src/ajax.js#L176

like image 131
Kevin B Avatar answered Nov 15 '22 08:11

Kevin B