为什么CSS选择器'table tr:not(tr:nth-​​child(even))'抛出TypeError?

时间:2019-01-22 15:30:25

标签: javascript css-selectors

此选择器为什么起作用:

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

虽然此选择器没有(引发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 个答案:

答案 0 :(得分:4)

  

虽然此选择器没有(引发TypeError):

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

:not()仅使用一个“简单选择器”,而tr:nth-child(even)不是一个选择器。

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

  

一个简单的选择器可以是类型选择器,通用选择器,属性选择器,类选择器,ID选择器或伪类。

任一是这里的重要关键字。这些选择器类型仅允许其中一种,而不是它们的组合。