首页 > 解决方案 > 如何捕获具有相同数据属性的多个 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 执行此操作的理想方法是什么。

标签: javascript

解决方案


可能这会帮助你

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>

?


推荐阅读