Why is CSS selector 'table tr:not(tr:nth-child

2019-08-23 10:32发布

问题:

Why does this selector work:

document.querySelectorAll('table tr:not(:nth-child(even))');

While this selector does not (throws a TypeError):

document.querySelectorAll('table tr:not(tr:nth-child(even))');

var query = (selector) => {
  return document.querySelectorAll(selector);
};
  
try {
  var select_a = 'table tr:not(:nth-child(even))';
  var select_b = 'table tr:not(tr:nth-child(even))';

  query(select_a).forEach((node) => {
    node.style.color = 'red';
  });

  query(select_b).forEach((node) => {
    node.style.color = 'blue';
  });
} catch (e) {
    query('div:nth-child(3)')[0].textContent = e.toString();
}
var query = (selector) => {
  return document.querySelectorAll(selector);
};
  
try {
  var select_a = 'table tr:not(:nth-child(even))';
  var select_b = 'table tr:not(tr:nth-child(even))';

  query(select_a).forEach((node) => {
    node.style.color = 'red';
  });

  query(select_b).forEach((node) => {
    node.style.color = 'blue';
  });
} catch (e) {
    query('div:nth-child(3)')[0].textContent = e.toString();
}
<table>
  <tr>
    <td>row 1 first-name</td>
    <td>row 1 last-name</td>
    <td>row-1 email</td>
  </tr>
  <tr>
    <td>row 2 first-name</td>
    <td>row 2 last-name</td>
    <td>row-2 email</td>
  </tr>
  <tr>
    <td>row 3 first-name</td>
    <td>row 3 last-name</td>
    <td>row-3 email</td>
  </tr>
  <tr>
    <td>row 4 first-name</td>
    <td>row 4 last-name</td>
    <td>row-4 email</td>
  </tr>
  <tr>
    <td>row 5 first-name</td>
    <td>row 5 last-name</td>
    <td>row-5 email</td>
  </tr>
</table>

<div>Why does select_a work but not select_b?</div>

<div></div>

回答1:

While this selector does not (throws a TypeError):

document.querySelectorAll('table tr:not(tr:nth-child(even))');

:not() only takes a “simple selector”, and tr:nth-child(even) isn’t one.

https://drafts.csswg.org/selectors-3/#simple-selectors-dfn:

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

Either is the important keyword here. Only one of those selector types is allowed, not combinations of them.