I have some jquery-like function:
function(elem) {
return $('> someselector', elem);
};
The question is how can i do the same with querySelector()
?
The problem is >
selector in querySelector()
requires parent to be explicitly specified. Is there any workaround?
If you know the tag name of the element that you’re looking into, then you can use it in the selector to achieve what you want.
For example if you have a
<select>
that has<option>
s and<optgroups>
, and you only want the<option>
s that are its immediate children, not the ones inside<optgoups>
:So, having a reference to the select element, you can — surprisingly — get its immediate children like this:
It seems to work in Chrome, Safari, and Firefox, but didn’t test in IEs. =/
If you want to eventually find direct children (and not e.g.
> div > span
), you can try Element.matches():That worked for me:
you will have to pass the @this keywork before the > when you want to search for immediate children.
You can't. There's no selector that will simulate your starting point.
The way jQuery does it (more because of a way that
qsa
behaves that is not to their liking), is that they check to see ifelem
has an ID, and if not, they temporarily add an ID, then create a full selector string.Basically you'd do:
This certainly isn't jQuery code, but from what I remember, it is basically what they do. Not just in this situation, but in any situation where you're running a selector from the context of a nested element.
Source code for Sizzle
The following is a simplified, generic method for running any CSS selector query over only direct children - it also accounts for combined queries, like
"foo[bar], baz.boo"
:Though it's not a full answer, you should keep an eye on the W3C Selector API v.2 which is already available in Google Chrome and Safari 7.x (both desktop and mobile), but as far as I have tested, still not there in Firefox and IE.