In the jQuery documentation for the child selector I saw this note:
Note: The
$("> elem", context)
selector will be deprecated in a future release. Its usage is thus discouraged in lieu of using alternative selectors.
I use this pattern all the time, usually like this:
$nodes.find('> children[something=morecomplicated] > somethingelse');
However, I don't understand what the "alternative selectors" they refer to could be. What is the right way to write a selector which traverses the immediate children of a context node? As a bonus, can anyone explain why this is depreciated? All the alternatives everyone is giving seem amazingly ugly.
Here are some things that don't work:
// does not guarantee that '.child' is an immediate child
$nodes.find('.child > .grandchild');
// this will return empty array in recent jQuery
// and will return full list of children in older jQuery
$nodes.children('.child > .grandchild');
// Anything like this which forces you to split up the selector.
// This is ugly and inconsistent with usual selector ease-of-use,
// and is a non-trivial conversion for long or complex selectors.
$nodes.children('.child').children('.grandchild');
// After all, no one would ever recommend
$nodes.find('.this').children('.that');
// instead of
$nodes.find('.this > .that');
The reason they are saying:
Note: The
$("> elem", context)
selector will be deprecated in a future release. Its usage is thus discouraged in lieu of using alternative selectors.
Is due to the comma followed by the context in the selector. E.g. $("> elem")
is fine however, $("> elem", context)
will be deprecated.
$("> elem", context)
is the same as $(context + "> elem")
.
A correct way of obtaining children and grandchildren is
$("elem").children('.child').children('.grandchild');
or
context.children('.child').children('.grandchild');
or
context.find('> .child > .grandchild');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With