querySelectorAll() -- selecting _immediate_ children of element

querySelector() and querySelectorAll() methods are exciting features, but they do not allow select _immediate_ children of reference element.

To address this lack, we could use following syntax:

ššššvar divs = refElement.querySelectorAll('> DIV');

Here 'divs' variable contains list of DIV elements that are immediate children (not just descendant elements) of reference element (refElement).

This syntax is extremely intuitive and BTW is supported in jQuery.

Other combinators (e.g. adjacent-sibling combinator) would have sense too, for example:

ššššvar span = h1.querySelector('+ H2 SPAN');

'span' variable here contains DOM reference to SPAN elements inside H2 element which is next sibling of H1 element:

šššš<h1>...</h1>
šššš<h2>... <span>...</span> ...</h2>

But fundamental missing demanded feature is ability to select _child_ elements of reference element ( querySelectorAll('> DIV') ).

Since usecases are purely script-level, CSSWG has nothing to do with this syntax. From selectors perspective, there is nothing new here: we have reference element (in CSS, a selector is used in place of concrete element), standard selector (DIV), and standard combinator between them.

An acceptable alternative to implied reference element would be using ':this' pseudoclass:

ššššvar divs = refElement.querySelectorAll(':this > DIV');
ššššvar span = h1.querySelector(':this + H2 SPAN');

Furthermore, :this pseudoclass would give us additional possibilities such as selecting descendant elements via selectors _all_ parts of which matches to descendants of reference element.

For example, following code will select all links that are descendants of _any_ paragraph (not necessarily descendants of reference element):

ššššrefElement.querySelectorAll('P A');

As opposed, this code:

ššššrefElement.querySelectorAll(':this P A');

would select links that are inside of paragraphs which _themselves_ are descendants of the reference element.

Probably most DRY, usable, and flexible solution would be to allow both syntaxes: implied reference element to use with combinators (where :this would be just redundant), and explicit :this to use in conjunction with descendant selectors (where it really gives additional useful possibilities missing in current querySelector spec and implementations).

Thanks.

P.S. The proposal has been originally posted in public-script-coord (http://lists.w3.org/Archives/Public/public-script-coord/2012JanMar/0078.html ) but it seems public-webapps is probably more appropriate place for this.

Received on Monday, 9 January 2012 14:46:54 UTC