javascript - 从 HTML 中获取带有适当空格的文本

标签 javascript jquery html text

使用 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/

相关文章:

javascript - jQuery 保持其他框未编辑状态

javascript - 在 JavaScript 中,如何为模态图库中的每个图像添加动画效果?

javascript - angularjs 无法读取未定义的属性

JQuery 从重复的 html 结构中选择 3 个链接中的 2 个

javascript - 基本初始化故障排除

javascript - php 按字母顺序分页

javascript - 如何在 ng-bind angularjs 中使用 toFixed(2)

javascript - 保存所选元素的 ID

html - jQuery Accordion 不会像它应该的那样下降

html - 图像大于视口(viewport)时不居中