简体   繁体   English

如何检测父元素是否具有 javascript 的特定子元素?

[英]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.

相关问题 如何通过单击父元素来检测子元素? - How can I detect a child element by clicking on a parent element? 如何使用JavaScript查找被单击的元素(或具有背景图像的最近的子元素或父元素)的背景图像? - How can I find the background image of a clicked element (or the nearest child or parent element that has a background image) using JavaScript? 如何隐藏具有给定类的所有元素的父元素,但父元素也具有特定的类? - How can I hide parent element of all elements with a given class, but the parent element also has a specific class? 如何选择具有动态ID的父元素的嵌套子元素? - How can I select a nested child element of a parent element that has a dynamic ID? javascript:仅在父元素处于活动状态且子元素具有特定类的情况下,才如何向子元素添加属性? - javascript: how to add an attribute to a child element ONLY if a parent element is active AND child element has a certain class? 如何检查父元素是否有子元素 - How to check if parent element has a child element 如何使用普通的纯Javascript检测Nav是否有子元素? - How to detect if Nav has child element using plain Plain Javascript? 我怎么知道一个元素是否有一个特定的 JavaScript 类? - How can I know if an element has a specific class with JavaScript? 如何检测特定元素? - How can I detect specific element is clicked? 如何根据子元素值对父元素排序? - How can I sort a parent element based on child element value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM