[英]How do I check if an element contains at least one direct text node
How do I check if an element contains at least one direct text node ?如何检查元素是否包含至少一个直接文本节点?
Given:鉴于:
<div id="a">
One <span>Two</span>
</div>
<div id="b">
<span>Three</span>
</div>
<div id="c">
Four
</div>
<div id="d"> </div>
And:和:
function containsDirectText(el) {
// using plain Javascript, not jQuery
}
Then:然后:
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)
You can check the nodeType
of the child nodes to find text nodes, but your example "b" that you want to return false
does have a text node — the spaces used to indent — so you have to exclude blank text nodes.您可以检查子节点的
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>
(I split your "d" case into the original empty div and the updated div with only whitespace) (我将您的“d”案例拆分为原始的空div 和仅包含空格的更新 div)
An element's childNodes
returns a NodeList
, so I use the spread operator to turn it into an Array, which has the .some(callback) method.一个元素的
childNodes
返回一个NodeList
,因此我使用扩展运算符将其转换为具有.some(callback)方法的数组。
some returns true if the callback function returns a truthy value for at least one element in the array, so I test each element to see if its nodeType is a TEXT_NODE and that the nodeValue is not empty.如果回调 function 返回数组中至少一个元素的真值,则some返回 true,因此我测试每个元素以查看其 nodeType 是否为 TEXT_NODE 并且 nodeValue 不为空。
If at least one child node fits that description, some returns true
so containsDirectText returns true.如果至少有一个子节点符合该描述,则some返回
true
,因此containsDirectText返回 true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.