[英]How to check if parent element has a child element
I have a parent element which includes child element.我有一个包含子元素的父元素。 But the child element appears only when the button click.
但是子元素只有在按钮单击时才会出现。
Initial parent element:初始父元素:
<div class="parent">
<!--v-if-->
</div>
When the button is clicked:单击按钮时:
<div class="parent">
<div class="child"></div>
</div>
So I want to see if the parent element has a child element or not.所以我想看看父元素是否有子元素。 How can I do it with javascript?
我怎样才能用javascript做到这一点?
el.hasChildNodes - This can do the job but it will also count the non-element nodes. el.hasChildNodes - 这可以完成这项工作,但它也会计算非元素节点。
el.children - This includes only element nodes. el.children - 这仅包括元素节点。
let parent1 = document.getElementById("parent1"); let parent2 = document.getElementById("parent2"); let parent3 = document.getElementById("parent3") console.log('Parent1 has child - ', parent1.hasChildNodes()); console.log('Parent1 has child - ', Boolean(parent1.children.length)); console.log('Parent2 has child - ', parent2.hasChildNodes()); console.log('Parent2 has child - ', Boolean(parent2.children.length)); console.log('Parent3 has child - ', parent3.hasChildNodes()); console.log('Parent3 has child - ', Boolean(parent3.children.length));
<!-- parent 1 --> <div id="parent1"></div> <!-- parent 2 --> <div id="parent2"> <div id="child1"></div> </div> <!-- parent 3 --> <div id="parent3"> <!-- comment --> </div>
That element does start out with child nodes (two text nodes and a comment node), just no element children.该元素确实以子节点(两个文本节点和一个注释节点)开始,只是没有元素子节点。
If you want to know if it has any element children, you can use firstElementChild
, which will be null
if the element doesn't have any child elements, or the first child element if it does.如果您想知道它是否有任何子元素,可以使用
firstElementChild
,如果该元素没有任何子元素,它将为null
,如果有,则为第一个子元素。
const x = document.querySelector(".parent"); console.log(`Before: ${.;x.firstElementChild}`); // Emulate replacing the comment node with an element node const div = document.createElement("div"); div.className = "child", x.replaceChild(div; x.childNodes[1]): console.log(`After; ${!!x.firstElementChild}`);
<div class="parent"> <!--v-if--> </div>
You can check the child node with the "hasChildNodes()" method:您可以使用“hasChildNodes()”方法检查子节点:
const parent = document.querySelector(".parent")
btnActions() => {
this.addAChild()
this.checkHasChild()
}
addAChild() => {
parent.innerHTML = `<div class="child"></div>`
}
checkHasChild() => {
console.log(parent.hasChildNodes())
}
https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.