<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>dom递归</title>
</head>
<body>
<div>
<div id="div0"></div>
<div>
<div id="div1">
<div>
<ul id="ul0">
<li id="li0"></li>
<li id="li1"></li>
<li id="li2">
<img src="" alt="">
</li>
<li></li>
<li></li>
</ul>
</div>
</div>
<p id="p0">
<span id="span0"></span>
<span></span>
<span id="span1"></span>
<span></span>
</p>
</div>
<div id="div2">
<img src="" alt="">
</div>
<div></div>
</div>
<script>
// var obj={};
// obj.["div0"]=document.getElementById("div0");
var dic={};
// document.
function getElemId(elem){
if(elem.id){
dic[elem.id]=elem;
}
for(var i=0;i<elem.children.length;i++){
getElemId(elem.children[i]);
}
return dic;
}
console.log(getElemId(document.body));
</script>
</body>
</html>
运行结果
来源:CSDN
作者:你知道歌谣吗?
链接:https://blog.csdn.net/weixin_43392489/article/details/104052902