[英]how can i detect if a parent element has a specific child element with javascript?
I have a div that has a "span" and I am dynamically adding "div" tags with a class to identify them, so my question is: how can I know if my parent "div" tag has new div tag children without counting the tag "span"?我有一个具有“跨度”的 div,并且我正在动态添加带有 class 的“div”标签来识别它们,所以我的问题是:我如何知道我的父“div”标签是否有新的 div 标签子项而不计算标签“跨度”? because my problem is that the e[i].children.length function is always considering the span title as a child因为我的问题是 e[i].children.length function 总是将跨度标题视为孩子
In summary I need to know how many child div tags the parent div has (excluding all other html tags that can be added)总之,我需要知道父 div 有多少子 div 标签(不包括所有其他可以添加的 html 标签)
let e = document.getElementsByClassName('classDiv') for (let i = 0; i < e.length; i++) { if (e[i].children.length > 0) { console.log("has children"); } else { console.log("has no children"); } }
<div id="parent" class="classDiv"> <span id="title">title</span> <div>children1</div> <div>children2</div> <div>children3</div> </div>
Try尝试
var e = document.querySelectorAll('#parent > div');
console.log(e.length ? "has children" : "has no children");
The >
selector is used to select elements with a specific parent >
选择器用于具有特定父级的 select 元素
document.getElementById("parent").getElementsByTagName("div")
Will return all the child element that are divs.将返回所有 div 的子元素。
You can also do the same with getElementsByClassName instead of getElementById, while iterating over the results, and using the same getElementsByTageName on each one.您也可以使用 getElementsByClassName 而不是 getElementById 执行相同的操作,同时迭代结果,并对每个结果使用相同的 getElementsByTageName。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.