该任务借助JavaScript查找一个元素是否具有子元素。我们将讨论几种技术。
方法:
- 选择父元素。
- 使用其中之一firstChild, childNodes.length, children.length属性, 以查找element是否具有子元素。
- hasChildNodes()方法也可以用于查找父节点的子节点。
<
!DOCTYPE HTML>
<
html >
<
head >
<
title >
How to check if element has
any children in JavaScript ?
<
/ title >
<
/ head >
<
body style = "text-align:center;
" >
<
h1 style = "color:green;
" >
lsbin
<
/ h1 >
<
div id = "div" >
<
p id = "GFG_UP" style =
"font-size: 19px;
font-weight: bold;
" >
<
/ p >
<
/ div >
<
button onclick = "GFG_Fun()" >
click here
<
/ button >
<
p id = "GFG_DOWN" style =
"color:green;
font-size:24px;
font-weight:bold;
" >
<
/ p >
<
script >
var parentDiv = document.getElementById("div");
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to check "
+ "whether element has children.";
function GFG_Fun() {
var ans = "Element <
div >
has no children";
if (parentDiv.hasChildNodes()) {
ans = "Element <
div >
has children";
}el_down.innerHTML = ans;
}
<
/ script >
<
/ body >
<
/ html >
输出如下:
在单击按钮之前:
文章图片
【如何检查元素在JavaScript中是否有任何子代()】单击按钮后:
文章图片
范例2:在这个例子中children.length属性用于确定< div> 元件。
<
!DOCTYPE HTML>
<
html >
<
head >
<
title >
How to check if element has
any children in JavaScript ?
<
/ title >
<
/ head >
<
body style = "text-align:center;
" >
<
h1 style = "color:green;
" >
lsbin
<
/ h1 >
<
div id = "div" >
<
p id = "GFG_UP" style =
"font-size: 19px;
font-weight: bold;
" >
<
/ p >
<
/ div >
<
button onclick = "GFG_Fun()" >
click here
<
/ button >
<
p id = "GFG_DOWN" style =
"color:green;
font-size:24px;
font-weight:bold;
" >
<
/ p >
<
script >
var parentDiv = document.getElementById("div");
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to "+
"check whether element has children.";
function GFG_Fun() {
var ans = "Element <
div >
has no children";
if (parentDiv.children.length >
0) {
ans = "Element <
div >
has children";
}el_down.innerHTML = ans;
}
<
/ script >
<
/ body >
<
/ html >
输出如下:
在单击按钮之前:
文章图片
单击按钮后:
文章图片
推荐阅读
- MongoDB python 删除数据并删除集合
- PHP SplFixedArray key()函数用法介绍
- 如何学习ReactJS(初学者完整指南)
- 很简单!Vue.js入门教程手把手教你学会Vue.js开发
- 经典排序算法之选择排序(Selection Sort)实现原理和代码实现及其应用详解
- 数据库快速索引原理!B树和B+树的实现原理和实例代码全解
- 你真的懂树吗(二叉树、AVL平衡二叉树、伸展树、B-树和B+树原理和实现代码详解)
- 经典线性结构之线性表、栈和队列数据结构详解和实例分析
- 码农进阶!数据结构、算法分析、算法复杂度、大O符号和算法分析实例详解