d...">

Translate jQuery selector to javascript querySelector

I am trying to replicate this jQuery selector using querySelector:

$("*:not(#player > div)")

I know that I can select all the elements with querySelector('*'), but how can I exclude the elements matching#player > div

+4
source share
2 answers

Most jQuery selectors can be ported to querySelector()or CSS, but not all of them, since jQuery extends some existing ones and also fully introduces non-standard selectors.

In your particular case, unlike jQuery, :not()it only accepts a simple CSS selector. #player > div- a complex selector consisting of two simple selectors and a combinator. See this question for details:

jQuery: not() CSS?

jQuery. #player > div , document.querySelectorAll('#player > div') , .

... , , :not(#player > div) , - > , :

:root, :not(#player) > div, #player > :not(div), :not(#player) > :not(div)

:

// The following JS + CSS should give all matching elements a 1px solid red border
$(':not(#player > div)').css('border-color', 'red');
* { margin: 10px; }
html::before { content: 'html - Match'; }
body::before { content: 'body - Match'; }

:root, :not(#player) > div, #player > :not(div), :not(#player) > :not(div) {
  border-style: solid;
  border-width: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>body > p - Match</p>
<div>body > div - Match</div>
<div>
  body > div:not(#player) - Match
  <p>:not(#player) > p - Match</p>
  <div>:not(#player) > div - Match</div>
</div>
<div id=player>
  body > div#player - Match
  <p>#player > p - Match</p>
  <div>
    #player > div - Non-match
    <div>#player > div:not(#player) > div - Match</div>
  </div>
</div>
Hide result

- , , matches() polyfill .

+3

, .

var el = Array.prototype.slice.call(document.querySelectorAll('*'),0)
el.splice(el.indexOf(document.querySelectorAll('html')),1)
0

Source: https://habr.com/ru/post/1599156/


All Articles