P粉1986706032023-08-14 14:15:14
Try something like this and see if it works:
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); } }
Using your example html, the output should be:
"That's the first text I need" "The second text I need" "The third text I need"
P粉3863180862023-08-14 13:23:13
You can iterate over the child nodes of <p>
and get the 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>