示例 1
只有沒有任何 HTML 元素的文本:
<td class="txt">
some text
</td>
示例 2
有文本和 HTML 元素的組合:
<td class="txt">
some text with <span>Elment HTML</span>
</td>
示例 3
只有 HTML 元素:
<td class="txt">
<span>only HTML Element</span>
</td>
我的嘗試:
let txt = document.querySelector('.txt').innerHTML;
if(/<.*?>/.test(txt)){
console.log('mixed text and tags!')
}else{
console.log('only text!')
}
而我怎么知道只有標簽沒有任何文字結合的情況。
這是正確的做法嗎?
uj5u.com熱心網友回復:
const div = document.querySelector('.txt');
if(div.innerText === div.innerHTML){
console.log('only text!')
}else{
console.log('mixed text and tags!')
}
uj5u.com熱心網友回復:
回圈遍歷子節點并檢查是否有任何非文本節點。
let children = Array.from(document.querySelector('.txt').childNodes);
if (children.every(node => node.nodeType == Node.TEXT_NODE)) {
console.log('only text');
} else {
console.log('mixed text and tags');
}
uj5u.com熱心網友回復:
您可能會尋找https://developer.mozilla.org/en-US/docs/Web/API/Element/children的 children 集合僅包含節點但忽略文本:
if (document.querySelector('.txt').children.length > 0) {
console.log('at least one node, possibly mixed with text')
} else {
console.log('no tags (might be only text or empty)')
}
uj5u.com熱心網友回復:
您可以使用元素的firstElementChild屬性。如果為 null,則沒有子元素。
let element = document.querySelector('.txt');
if (element.firstElementChild){
console.log('mixed text and tags!')
}else{
console.log('only text!')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/510236.html
上一篇:測量DOM節點
