需求:获取页面某个元素上所有后代元素,以便于给某些元素绑定事件或者修改样式等操作。
结果如图:
页面代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
display: inline-block;
box-sizing: border-box;
border-radius: 5px;
border: 1px solid #000;
width: 100px;
height: 100px;
padding: 10px;
}
.container {
width: 1000px;
height: auto;
background-color: rgba(0, 0, 0, 0.6);
}
.son {
width: 350px;
height: 350px;
background-color: rgba(164, 157, 157, 0.6);
}
.grandson {
width: 200px;
height: 200px;
background-color: rgba(217, 123, 123, 0.6);
}
.box {
width: 50px;
height: 50px;
background-color: rgba(123, 217, 132, 0.6);
}
</style>
</head>
<body>
<div class="container">
<div class="son">
<div class="grandson">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
<div class="son">
<div class="grandson">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
</div>
<script>
// 需求:获取页面某个元素上所有后代元素
(function () {
window.onload = function () {
// 获取要抽取后代元素的节点
const outer = document.querySelector('.container')
const getAllDomNode = function (dom, property) {
let res = [];
res.push(dom);
if (dom[property] && dom[property].length > 0) {
for (let i = 0; i < dom[property].length; i++) {
// 递归子元素
res = res.concat(getAllDomNode(dom[property][i], property));
}
}
return res;
}
const doms = getAllDomNode(outer, 'children');
console.log('@', doms);
// todo something...
}
})();
</script>
</body>
</html>