CSS pseudo selector to select current element in querySelector?

That a CSS pseudo selector can select an element on its own?

For example, this doesn't 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 that something like this:

Array.prototype.map.call(document.querySelectorAll('.program_record_outer'), programBox => {
    return programBox.querySelector(':self > div')
});

      

However, :self

not a thing, but :root

refers to the document root, so how do I refer to the current context?

+3


source to share


1 answer


In some of the latest browsers ( Chrome, Firefox 32+, Opera 15+ and Safari 7.0+ ), you can use :scope

when calling 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>
      

Run codeHide result


+7


source







All Articles