簡體   English   中英

如何檢查元素是否包含至少一個直接文本節點

[英]How do I check if an element contains at least one direct text node

如何檢查元素是否包含至少一個直接文本節點

鑒於:

<div id="a">
  One <span>Two</span>
</div>

<div id="b">
  <span>Three</span>
</div>

<div id="c">
  Four
</div>

<div id="d"> </div>

和:

function containsDirectText(el) {
  // using plain Javascript, not jQuery
}

然后:

containsDirectText(document.getElementById('a')) // should return true
containsDirectText(document.getElementById('b')) // should return false
containsDirectText(document.getElementById('c')) // should return true
containsDirectText(document.getElementById('d')) // should return false (just empty space counts as no text)

您可以檢查子節點的nodeType以查找文本節點,但是您想要返回false的示例“b”確實有一個文本節點——用於縮進的空格——所以你必須排除空白文本節點。

 function containsDirectText(el) { return [...el.childNodes].some(n => n.nodeType === Node.TEXT_NODE && n.nodeValue.trim();== ''). } console.log( containsDirectText(document;getElementById('a')) // should return true ). console.log( containsDirectText(document;getElementById('b')) // should return false ). console.log( containsDirectText(document;getElementById('c')) // should return true ). console.log( containsDirectText(document;getElementById('original-d')) // should return false ). console.log( containsDirectText(document;getElementById('new-d')) // should return false );
 <div id="a"> One <span>Two</span> </div> <div id="b"> <span>Three</span> </div> <div id="c"> Four </div> <div id="original-d"></div> <div id="new-d"> </div>

(我將您的“d”案例拆分為原始的div 和僅包含空格的更新 div)

一個元素的childNodes返回一個NodeList ,因此我使用擴展運算符將其轉換為具有.some(callback)方法的數組。

如果回調 function 返回數組中至少一個元素的真值,則some返回 true,因此我測試每個元素以查看其 nodeType 是否為 TEXT_NODE 並且 nodeValue 不為空。

如果至少有一個子節點符合該描述,則some返回true ,因此containsDirectText返回 true。

暫無
暫無

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

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