Reputation: 4162
I have this block of HTML:
<div class="cart">
<a href="/4S101W.html"><b>Gray T-shirt</b></a><br>
Size:M<br>
Style:1722322<br>
<div>Qty:2</div><div>Price: $14.95</div>
<div>
How can I retrieve the style number, in this case, 1722322, from the above block of HTML?
I was trying
console.log(jQuery('div.cart:contains("Style")').html().split('<br>'));
But it's returns the whole block.
Upvotes: 0
Views: 64
Reputation: 28751
Do this
var divcontent=$('div.cart').text();
var arr=divcontent.split('Style:');
var styleValue = arr[1].split(':')[0];
alert(parseInt(styleValue));//parseInt extracts number from string array element.
Upvotes: 1
Reputation: 1641
Or you could try....
document.querySelector('div.cart').textContent.split('Style:')[1].split('\n')[0]
Upvotes: 0
Reputation: 11297
How about Regex?
console.log(
($('.cart').text()).match(/(?:Style:)(\d+)/)[1]
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="cart">
<a href="/4S101W.html"><b>Gray T-shirt</b></a><br>
Size:M<br>
Style:1722322<br>
<div>Qty:2</div><div>Price: $14.95</div>
<div>
Upvotes: 0
Reputation: 74420
You could retrieve the relevant textNode and parse it to number, e.g:
var num = +$('.cart').contents().filter(function(){
return this.nodeType === 3 && this.nodeValue.indexOf('Style:') > -1
}).get(0).nodeValue.trim().replace('Style:','');
var num = +$('.cart').contents().filter(function() {
return this.nodeType === 3 && this.nodeValue.indexOf('Style:') > -1
}).get(0).nodeValue.trim().replace('Style:', '');
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cart">
<a href="/4S101W.html"><b>Gray T-shirt</b></a>
<br>Size:M
<br>Style:1722322
<br>
<div>Qty:2</div>
<div>Price: $14.95</div>
<div>
Upvotes: 1