JavaScript - 在JavaScript中获取DOM元素中包含的文本?

3

我有一个包含一些子元素的 <div>,其中包含以下文本:

<div class="accordion-item__panel">
    <h5>The baby tears the pages of the</h5>
    <p>books with her <span>hands.</span></p>
    <p class="body-small">What is the funniest thing the baby does?</p>
</div>

我希望提取accordion-item__panel DIV内的文本并输出结果:

The baby tears the pages of the books with her hands. What is the funniest thing the baby does?

当前输出:

The baby tears the pages of the books with her hands. hands. What is the funniest thing the baby does?

在查询元素时,"hands." 被重复出现了两次,因此添加了两次。

JavaScript:

let desc = "";
const descItems = item.querySelectorAll('.accordion-item__panel *');
descItems.forEach((item, index) => {
    if(index === 0){
        desc += item.innerText;
    }else{
        desc += ' ' + item.innerText;
    }
});

console.log("desc", desc);

Run this:

let desc = "";
const descItems = document.querySelectorAll('.tcb__accordion-item__panel *');
descItems.forEach((item, index) => {
    if(index === 0){
        desc += item.innerText;
    }else{
        desc += ' ' + item.innerText;
    }
});
console.log("desc", desc);
.accordion-item__panel{
  display:block;
  width: 300px;
}

.accordion-item__panel *{
  padding: 0;
  margin: 0;
}
<div class="accordion-item__panel">
  <h5>The baby tears the pages of the</h5>
  <p>books with her <span>hands.</span></p>
  <p class="body-small">What is the funniest thing the baby does?</p>
</div>

2个回答

5
你可以选择父元素,然后访问 textContent 属性。它会将子元素的内容以你想要的格式拼接起来。
我们还可以利用正则表达式去除独立子元素中的多余空格,并使用字符串 trim 方法修剪前导/尾随空格。

const parentElement = document.querySelector('.accordion-item__panel');
console.log(parentElement.textContent);
console.log(parentElement.textContent.replace(/\s{2,}/g, " ").trim());
<div class="accordion-item__panel">
    <h5>The baby tears the pages of the</h5>
    <p>books with her <span>hands.</span></p>
    <p class="body-small">What is the funniest thing the baby does?</p>
</div>


2

textContent可以获取不带标签的纯文本。然后,您可以使用replace函数来删除换行符和多个空格。就像这样:

const div = document.querySelector('div.accordion-item__panel');
console.log( div.textContent.replace(/(\r\n|\n|\r|\s{2,})/gm, "") ); 
<div class="accordion-item__panel">
    <h5>The baby tears the pages of the</h5>
    <p>books with her <span>hands.</span></p>
    <p class="body-small">What is the funniest thing the baby does?</p>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接