我有一个包含一些子元素的 <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>