Reputation: 283223
What's the CSS pseudo-selector to select an element's self?
For example, this does not work:
Array.prototype.map.call(document.querySelectorAll('.program_record_outer'), programBox => {
return programBox.querySelector('> div')
});
DOMException: Failed to execute 'querySelector' on 'Element': '> div' is not a valid selector.
But I believe something like this would:
Array.prototype.map.call(document.querySelectorAll('.program_record_outer'), programBox => {
return programBox.querySelector(':self > div')
});
However, :self
isn't a thing, and :root
refers to the document root, so how do I refer to the current context?
Upvotes: 29
Views: 17832
Reputation: 185280
&
should work in browsers supporting CSS nesting.
element.querySelector('& > div')
Upvotes: 2
Reputation: 28164
Another option (which I haven't seen mentioned) is to use *
, e.g. * > div
.
Upvotes: -3
Reputation: 16777
In some of the latest browsers (Chrome, Firefox 32+, Opera 15+, and Safari 7.0+) you can use the :scope
selector in calls to querySelector
and querySelectorAll
:
let result = [...document.querySelectorAll('.program_record_outer')].map(
programBox => programBox.querySelector(':scope > div')
)
console.log(result)
<div class="program_record_outer">
<div>1</div>
</div>
<div class="program_record_outer">
<div>2</div>
</div>
<div class="program_record_outer">
<div>3</div>
</div>
Upvotes: 48