javascript - 如何捕获具有相同数据属性的多个 div 的文本?
问题描述
多个 div 包含相同的 html5 数据属性
具有相同的值。每个 div 内都有 b 和 p 标签,它们具有相同的 html 5 数据属性和相同的值。
要求是以这种格式捕获每个 div 值。< b 标签文本 p 标签文本 | b2 标签文本 p2 标签文本 | b3 标签文本 p3 标签文本 > 等等。示例结果--- T1 标题1 D1 描述1 | T2 标题2 D2 描述2 | T3 标题3 D3 描述3
这是div代码
<div data-v-46636d4a="" class="panel_2N_jF">
<div data-v-46636d4a="" data-purpose="selected-prescription">
<b data-v-46636d4a="" data-purpose="prescription-name">T1 title1</b>
<p data-v-46636d4a="" data-purpose="prescription-description">D1 description1</p>
</div>
<div data-v-46636d4a="" data-purpose="selected-prescription">
<b data-v-46636d4a="" data-purpose="prescription-name">T2 title 2</b>
<p data-v-46636d4a="" data-purpose="prescription-description">D2 description2</p>
</div>
<div data-v-46636d4a="" data-purpose="selected-prescription">
<b data-v-46636d4a="" data-purpose="prescription-name">T3 title3</b>
<p data-v-46636d4a="" data-purpose="prescription-description">D3 description3</p>
</div>
</div>
我使用了简单的这段代码:
console.log(
document.querySelector("body > div:nth-child(1) > div:nth-child(1) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(1) > p").textContent + ' ' + '|'
+ document.querySelector("body > div:nth-child(1) > div:nth-child(2) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(2) > p").textContent + ' ' + '|'
+ document.querySelector("body > div:nth-child(1) > div:nth-child(3) > b").textContent + ' '
+ document.querySelector("body > div:nth-child(1) > div:nth-child(3) > p").textContent
);
但是为多个 div 执行此操作的理想方法是什么。
解决方案
可能这会帮助你
var Div_Childs = document.querySelector('div[data-v-46636d4a]').children;
var message = [];
for( var i = 0; i < Div_Childs.length; i++ ) {
message.push( Div_Childs[i].querySelector('b').textContent + ' '
+ Div_Childs[i].querySelector('p').textContent );
}
console.log (message.join(' | '));
<div data-v-46636d4a class="panel_2N_jF">
<div data-v-46636d4a data-purpose="selected-prescription">
<b data-v-46636d4a data-purpose="prescription-name">T1 title1</b>
<p data-v-46636d4a data-purpose="prescription-description">D1 description1</p>
</div>
<div data-v-46636d4a data-purpose="selected-prescription">
<b data-v-46636d4a data-purpose="prescription-name">T2 title 2</b>
<p data-v-46636d4a data-purpose="prescription-description">D2 description2</p>
</div>
<div data-v-46636d4a data-purpose="selected-prescription">
<b data-v-46636d4a data-purpose="prescription-name">T3 title3</b>
<p data-v-46636d4a data-purpose="prescription-description">D3 description3</p>
</div>
</div>
?
推荐阅读
- oracle - 在 Oracle Kubernetes 集群和对象存储上设置 Spinnaker
- node.js - 什么是非 socket.io 进程的示例?
- pyspark - 尝试更改 pyspark 中的数据类型时获取 null
- javascript - 如何删除 Chart.js 条形图的底部刻度
- php - 如何使用 gettext 翻译 MySQL 中的数据?
- java - Android - 如何在 rrule 中创建带有“直到”日期的重复事件?
- amazon-web-services - aws elasticsearch 创建了 2 个实例,但说它有 3 个节点
- ruby - 带有变量名的 Ruby 打印数组
- python - 了解神经网络中的最佳模型
- javascript - 设置尝试后无法设置对象状态 useState 反应原生地图