JavaScript 如何判断父元素是否包含子元素
在JavaScript中, children 属性返回给定元素的子元素数组。
为了检查父元素(假设为x)是否包含子元素(假设为y),我们可以使用 children 属性获取x的所有子元素数组,然后检查获取到的数组是否包含y。
使用JavaScript获取父元素的子元素,可以参考这篇文章的代码实现。
语法:
var childrens=document.getElementById(parentElement).children;
方法:
- 选择父元素
- 使用 children 属性来获取父元素的子元素数组。
- 遍历数组以查找子元素,如果找到,则返回 true。
- 如果找不到,则返回 false。
示例:
<!DOCTYPE html>
<html>
<head>
<body>
<div id="parent">
<h2>This is parent div</h2>
<p>This div contains various elements inside it.</p>
<p>Each HTML element is inside this div is child div</p>
<p>We need to check if element whose id is <b>'geeks'</b>
is a child div of given parents div</p>
<p id="geeks" style="color:green;">GeeksforGeeks</p>
<button onclick="check('parent','geeks')">Check</button>
<p id="result"></p>
</div>
</body>
<script>
function check(parentElement,childElement)
{
if(isChild(parentElement,childElement))
document.getElementById('result').innerHTML
=childElement+' is child of given parent element';
else
document.getElementById('result').innerHTML
=childElement+' is not child of given parent element';
}
/* Function that returns true if parent
element contains child element */
function isChild(parentElement,childElement)
{
var childrens =
document.getElementById(parentElement).children;
console.log(parentElement);
for(let i=0;i<childrens.length;i++)
{
if(childrens[i]==document.getElementById(childElement))
{
return true;
}
}
return false;
}
</script>
</head>
</html>
输出: