簡體   English   中英

如何檢測父元素是否具有 javascript 的特定子元素?

[英]how can i detect if a parent element has a specific child element with javascript?

我有一個具有“跨度”的 div,並且我正在動態添加帶有 class 的“div”標簽來識別它們,所以我的問題是:我如何知道我的父“div”標簽是否有新的 div 標簽子項而不計算標簽“跨度”? 因為我的問題是 e[i].children.length function 總是將跨度標題視為孩子

總之,我需要知道父 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>

嘗試

var e = document.querySelectorAll('#parent > div');
console.log(e.length ? "has children" : "has no children");

>選擇器用於具有特定父級的 select 元素

document.getElementById("parent").getElementsByTagName("div")

將返回所有 div 的子元素。

您也可以使用 getElementsByClassName 而不是 getElementById 執行相同的操作,同時迭代結果,並對每個結果使用相同的 getElementsByTageName。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM