Matt Ball
Matt Ball

Reputation: 359836

Is there a sexier way to write this jQuery selector?

I want to select all the children of the body element before element with id foo (which is a child of body). Since it doesn't look like there are :before() or :after() selectors, I've got it working like this:

$('body > :first').nextUntil('#foo').andSelf();

but it seems kludgy. Could this be done with fewer function calls, or more efficiently? Maybe something akin to $('body > *:before(#foo)') ?

Upvotes: 3

Views: 190

Answers (1)

jAndy
jAndy

Reputation: 236022

It's not that kludgy. Infact, using your example with "*" within the selector is WAY slower than calling functions.

So, I would suggest using one function more in your original selector:

$('body').children().first().nextUntil('#foo').andSelf() 

most of those functions use a simple array slice to reduce the set, where selecters have to traverse the DOM.

Upvotes: 4

Related Questions