代码
/**
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
实例
html
<div id="img" style="border: 1px solid red">
<h3 id="testStr" style="color: #000">sdjfosjdf</h3>
</div>
<div class="node1" style="color: red"><h1>这是另外的标签</h1></div>
js
const node = document.getElementById('img')
function callback(e){
console.log('hasParent(e.target, node)',hasParent(e.target, node))
}
window.addEventListener('click', callback)
说明:
- 点击h3标签或者id为img的div返回true. 其余返回false
网友评论