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"
嘗試像這樣做,看看是否有效:
使用您的範例html,輸出應為:
您可以迭代
的子節點,並取得任何非空白內容的
nodeType === Node.TEXT_NODE
: