P粉1986706032023-08-14 14:15:14
尝试像这样做,看看是否有效:
html = `your sample html above` domdoc = new DOMParser().parseFromString(html, "text/html") result = domdoc.evaluate('//text()[not(ancestor::span)]', domdoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); for (let i = 0; i < result.snapshotLength; i++) { target = result.snapshotItem(i).textContent.trim() if (target.length > 0) { console.log(target); } }
使用您的示例html,输出应为:
"That's the first text I need" "The second text I need" "The third text I need"
P粉3863180862023-08-14 13:23:13
您可以迭代 <p>
的子节点,并获取任何非空内容的 nodeType === Node.TEXT_NODE
:
for (const e of document.querySelector("p").childNodes) { if (e.nodeType === Node.TEXT_NODE && e.textContent.trim()) { console.log(e.textContent.trim()); } } // 或者创建一个数组: const result = [...document.querySelector("p").childNodes] .filter(e => e.nodeType === Node.TEXT_NODE && e.textContent.trim() ) .map(e => e.textContent.trim()); console.log(result);
<p> <span class="hidden-text"> <span class="ft-semi">Count:</span> 31 <br> </span> <span class="ft-semi">Something:</span> That's the first text I need <span class="hidden-text"> <span class="ft-semi">Something2:</span> </span> The second text I need <br> <span class="ft-semi">Something3:</span> The third text I need </p>