<section data-reactid="56">
<h3 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 & WILSON</span>
</section>
I have a HTML snippet on my "Order Details" page where I want to dynamically get the value of the store number (starting with #). Is there any way using which I can loop through this child elements and get the value starting with #?
CodePudding user response:
Use can use document.querySelectorAll()
to get all the child element first. Then use forEach
to loop through and then use Regex - RegExp.match()
to get the exactly number that start with #
References:
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 data-reactid="56">
<h3 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 & WILSON</span>
</section>