views:

114

answers:

2

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)') ?

+4  A: 

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.

Kind Regards

--Andy

jAndy
`first()` returns the first element of the matched set (like using `$($('body')[0])`), not the first child.
Matt Ball
...so it would have to be `$('body').children().first().nextUntil('#foo').andSelf()`
Matt Ball
*Any* selector using the non-standard jQuery-only selectors will be slow compared to standard CSS selectors like `body`. This is because standard selectors can be passed off to the fast native `querySelectorAll` method in modern browsers. Always use the method version (like `first()`) in preference to the selector version unless you really have no other choice.
bobince
jAndy - I modified your answer so that it actually works, as per my earlier comment.
Matt Ball
A: 

I'm guessing that you could be new to jQuery? When I was new, It took me a while to get used to how everything was written, and that the semantics of JavaScript won't look as nice as nested HTML, etc. Eventually you'll get used to it, and efficiency will look the sexiest to you!

Happy coding!

Kyle