I am going to check if an html element contains it's own text.
Examples are
<div>Text<tag></tag>Text</div>
and <div>Text</div>
.
Some thing that not fit is <div><tag></tag><p></p></div>
My code snippet is
flag = false;
for ( var j = 0; j < item.childNodes.length; j ++){
if(item.childNodes[j].tagName == ""){
flag = true;
}
}
But it's not working, can someone help me with this?
What I expected was
<div>Text<tag></tag>Text</div>
's child nodes are Text
, <tag></tag>
and Text
. But it's not.
如果要检测文本节点子节点,请检查nodeType是否为TEXT_NODE而不是tagName是否为空字符串:
var flag = Array.from(item.childNodes).some(child => child.nodeType === child.TEXT_NODE);
You can use a combination of String.trim()
and the element's .textContent
property.
HTML
<div>
<p>hello</p>
</div>
JS
String.trim(document.querySelector('div').textContent); //"hello"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.