Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the new proper way to use a child selector with a context node in jQuery?

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');
like image 822
Francis Avila Avatar asked Dec 06 '11 20:12

Francis Avila


1 Answers

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');
like image 117
Dan Avatar answered Oct 05 '22 05:10

Dan