Reputation: 4392
Quick question - is it possible to extend jQuery selectors to change the resultset (for example) via traversal instead of just by filtering an existing set?
To clarify - I don't want the selector equivalent of a call to $.filter()
- I want something closer to $('foo:nth-child(n)')
or $('foo:eq(n)')
, where I can specify exactly which elements are returned by the selector. Any thoughts would be appreciated.
Edit: here's an example of what I want to implement:
$.expr[':']['nth-parent'] = function(deTarget, iIndex, aProperties, aStack) {
var iN, $currentElement;
if(!deTarget)
return;
if(!aProperties || aProperties.length < 4 || isNaN(iN = parseInt(aProperties[3])) || iN < 0)
throw('jQuery.nth-parent(N) requires a non-negative integer argument');
$currentElement = $(deTarget);
while(--iN >= 0)
$currentElement = $currentElement.parent();
aStack = $currentElement.length ? [$currentElement.get(0)] : [];
return aStack.length ? true : false;
};
So, ultimately, I'd want the new aStack
array returned as the result set, in this particular case.
Upvotes: 1
Views: 1179
Reputation: 630549
Yes you can do this, a proper example here would be what you're after in the question, here's how :eq()
is implemented:
jQuery[":"].eq = function(elem, i, match) {
return match[3] - 0 === i;
};
The signature has one more parameter, stack
, like this:
function(elem, index, match, stack)
stack
is the set of all elements, if you need use that in your filtering.
Upvotes: 1
Reputation: 237965
I think you mean you want a custom selector with a parameter:
$.expr[':'].heightAbove = function(obj, idx, meta, stack) {
return ($(this).height() > parseInt(meta, 10));
};
You can then call this as
$('div:heightAbove(40)');
to select divs with a height above 40px.
Upvotes: 1
Reputation: 10857
This link should help you with what you need: http://jquery-howto.blogspot.com/2009/06/custom-jquery-selectors.html
But to answer your question yes it is possible to create custom selectors.
Upvotes: 1