选择符Selectors API
1. querySelector()
document.querySelector(".bar").style.backgroundColor = "red";
document.querySelector(".bar, .foo").style.backgroundColor = "red";
document.querySelector(".bar.foo").style.backgroundColor = "red";
- 替代
document.getElementById()
2. querySelectorAll()
- 返回NodeList对象
- 替代
document.getElementsByClassName()
3. matchesSelector()
- 返回是否匹配选择符【有兼容性问题,Chrome支持webkitMatchesSelector()】
- 替代
ele.className === "bar foo"
4. 实例(阿里前端面试题)
- 页面上有一个表格,列表的每一行有一个删除按钮,点击后可以删除该行,请用原生javascript对按钮的删除批量事件
<html>
<head>
<title>表格</title>
<style>
#table {
width: 600px;
background: #fff;
margin: 0;
padding: 0;
}
.item {
display: flex;
text-align: left;
list-style-type: none;
width: 600px;
height: 20px;
line-height: 20px;
font-size: 14px;
border-bottom: 1px solid #999999;
}
.content {
padding-left: 10px;
width: 400px;
}
.btn {
width: 200px;
text-align: center;
}
</style>
</head>
<body>
<ul id="table">
<li class="item"><span class="content">Item1</span><a class="J_Btn btn" href="javascript:void(0);">x</a></li>
<li class="item"><span class="content">Item2</span><a class="J_Btn btn" href="javascript:void(0);">x</a></li>
<li class="item"><span class="content">Item3</span><a class="J_Btn btn" href="javascript:void(0);">x</a></li>
</ul>
<script>
var buttons = document.querySelectorAll(".J_Btn.btn");
for(let i = 0; i < buttons.length; i++){
buttons[i].addEventListener("click", function(e){
e.target.parentNode.remove();
})
}
var table = document.querySelector("#table");
table.addEventListener("click", function(e){
if(e.target.webkitMatchesSelector(".J_Btn.btn")){
e.target.parentNode.remove();
}
})
</script>
</body>
</html>