Dan*_*ith 3 html javascript foreach children queryselector
我有一个<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>
Run Code Online (Sandbox Code Playgroud)
我想要 DIV 中包含的文本accordion-item__panel和输出,例如:
The baby tears the pages of the books with her hands. What is the funniest thing the baby does?
Run Code Online (Sandbox Code Playgroud)
电流输出:
The baby tears the pages of the books with her hands. hands. What is the funniest thing the baby does?
Run Code Online (Sandbox Code Playgroud)
添加了“手”。两倍,因为它在查询元素时保留了两次。
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 Code Online (Sandbox Code Playgroud)
运行这个:
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);Run Code Online (Sandbox Code Playgroud)
.accordion-item__panel{
display:block;
width: 300px;
}
.accordion-item__panel *{
padding: 0;
margin: 0;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
您只需选择父元素并访问该textContent属性即可。它将按照您想要的格式有效地连接子级的内容。
我们还可以使用一些正则表达式从单独的子元素中删除多余的空格,并使用 String 方法修剪前导/尾随空格trim。
const parentElement = document.querySelector('.accordion-item__panel');
console.log(parentElement.textContent);
console.log(parentElement.textContent.replace(/\s{2,}/g, " ").trim());Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1107 次 |
| 最近记录: |