使用 jQuery 从 HTML 中提取文本很容易 .text()
方法...
$("<p>This <b>That</b> Other</p>").text() == "This That Other"
但是如果单词/元素之间没有空格,那么文本就会被连接起来......
$("<p>This <b>That</b><br/>Other</p>").text() == "This ThatOther"
Desired: "This That Other"
$("<div><h1>Title</h1><p>Text</p></div>").text() == "TitleText"
Desired: "Title Text"
有没有什么方法可以从 HTML 中获取所有文本(使用 .text()
或其他方法),这意味着上面的示例会按预期出现?
最佳答案
您可以遍历 DOM 树以查找 nodeType 为 3
的节点(文本节点)。当你找到一个时,将它添加到一个数组中。如果找到非文本节点,可以将其传回函数继续寻找。
function innerText(element) {
function getTextLoop(element) {
const texts = [];
Array.from(element.childNodes).forEach(node => {
if (node.nodeType === 3) {
texts.push(node.textContent.trim());
} else {
texts.push(...getTextLoop(node));
}
});
return texts;
}
return getTextLoop(element).join(' ');
}
/* EXAMPLES */
const div = document.createElement('div');
div.innerHTML = `<p>This <b>That</b><br/>Other</p>`;
console.log(innerText(div));
const div2 = document.createElement('div');
div2.innerHTML = `<div><h1>Title</h1><p>Text</p></div>`;
console.log(innerText(div2));
关于javascript - 从 HTML 中获取带有适当空格的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59144133/