循环遍历类的第n个子级,并动态获取以#开头的值



<section class="Test-order-details-delivery-info" data-reactid="56">
<h3 class="heading__small" data-reactid="57">Pickup address</h3>
<span data-reactid="58">
<!-- react-text: 59 --> <!-- /react-text -->
</span>
<!-- I want to get this value: 2840 -->
<span data-reactid="60">Test Store #2840</span>
<span data-reactid="61">1500 W WILSON AVE</span>
<span data-reactid="62">
<!-- react-text: 63 -->Chicago<!-- /react-text --><!-- react-text: 64 -->, <!-- /react-text --><!-- react-text: 65 -->IL<!-- /react-text --><!-- react-text: 66 --> <!-- /react-text --><!-- react-text: 67 -->60640<!-- /react-text -->
</span>
<span data-reactid="68">CLARK &amp; WILSON</span>
</section>

我在我的";订单详细信息";页面,我想在其中动态获取商店编号的值(以#开头(。有没有什么方法可以让我循环遍历这些子元素并获得以#开头的值?

Use可以使用document.querySelectorAll()首先获取所有子元素。然后使用forEach循环通过,然后使用Regex - RegExp.match()获得以#开头的确切数字

参考文献:

  • Regex文档
  • Regex在线生成器
  • 了解Regex语法

document.querySelectorAll("section > *")
.forEach(el => {
const text = el.textContent;
const regex = new RegExp('#[0-9]+', 'g');
if (text.match(regex)) {
console.log(regex.exec(text)[0]);
}
})
<section class="Test-order-details-delivery-info" data-reactid="56">
<h3 class="heading__small" data-reactid="57">Pickup address</h3>
<span data-reactid="58">
<!-- react-text: 59 --> <!-- /react-text -->
</span>
<!-- I want to get this value: 2840 -->
<span data-reactid="60">Test Store #2840</span>
<span data-reactid="61">1500 W WILSON AVE</span>
<span data-reactid="62">
<!-- react-text: 63 -->Chicago<!-- /react-text --><!-- react-text: 64 -->, <!-- /react-text --><!-- react-text: 65 -->IL<!-- /react-text --><!-- react-text: 66 --> <!-- /react-text --><!-- react-text: 67 -->60640<!-- /react-text -->
</span>
<span data-reactid="68">CLARK &amp; WILSON</span>
</section>

最新更新