问题描述
我有一个包含用户列表的表,我想在事件中隐藏所有重复项。下图中的示例隐藏了第二个tr#user-3。
但是当我尝试使用temp1.querySelectorAll('tr:not(#user-3:first)')
时,它没有返回任何节点,而是带来了无效的选择器错误。可能是什么原因,我该如何解决?
解决方法
:first不是CSS规范的一部分,这是jQuery特定的。
要访问第一个和最后一个元素,请尝试。
var nodes = temp1.querySelectorAll('tr');
var first = nodes[0];
var last = nodes[nodes.length- 1];
,
您可以改用querySelector()
。它总是使您获得与选择器匹配的第一个元素。
const firstEl = temp1.querySelector('tr');
,
对于给定的问题,我不知道出了什么问题。但是,下面的代码似乎可以正常工作。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table class="tables">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr id="user3">
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr id="user3">
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr id="user3">
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
</table>
</body>
<script>
window.onload = function(){
var table = document.querySelectorAll(".tables tr#user3:not(:nth-child(2))");
//console.log(table);
table.forEach(el => {
el.style.backgroundColor = "red";
})
}
</script>
</html>
该代码还可以与last-child