1 回答
TA贡献1936条经验 获得超6个赞
<div class="first">
<div class="first-child"></div>
</div>
<div class="second">
<div class="second-child">
<div class="second-child-child"></div>
</div>
</div>
<script type="text/javascript">
var a = document.querySelector('.first-child');
var b = document.querySelector('.second-child-child');
var c = document.querySelector('.first');
var d = document.querySelector('.second');
function isChildOf(child, parent) {
var parentNode;
if(child && parent) {
parentNode = child.parentNode;
while(parentNode) {
if(parent === parentNode) {
return true;
}
parentNode = parentNode.parentNode;
}
}
return false;
}
console.log(isChildOf(a, b));
console.log(isChildOf(b, d));
console.log(isChildOf(a, c));
</script>
添加回答
举报