怎么判断某个dom节点是否包含某个dom节点?

js有个contains的方法来判断是否为子节点
我想问下这个是怎么实现的呢?
原理是什么呢?

largeQ
浏览 4406回答 1
1回答

LEATH

<div class="first">&nbsp; &nbsp; <div class="first-child"></div></div><div class="second">&nbsp; &nbsp; <div class="second-child">&nbsp; &nbsp; &nbsp; &nbsp; <div class="second-child-child"></div>&nbsp; &nbsp; </div></div><script type="text/javascript">&nbsp; &nbsp; var a = document.querySelector('.first-child');&nbsp; &nbsp; var b = document.querySelector('.second-child-child');&nbsp; &nbsp; var c = document.querySelector('.first');&nbsp; &nbsp; var d = document.querySelector('.second');&nbsp; &nbsp; function isChildOf(child, parent) {&nbsp; &nbsp; &nbsp; &nbsp; var parentNode;&nbsp; &nbsp; &nbsp; &nbsp; if(child && parent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parentNode = child.parentNode;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while(parentNode) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(parent === parentNode) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parentNode = parentNode.parentNode;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; console.log(isChildOf(a, b));&nbsp; &nbsp; console.log(isChildOf(b, d));&nbsp; &nbsp; console.log(isChildOf(a, c));</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript