£50
£50
£50

Apply jQuery formula to individual div values that contain certain words in class

24 Views Asked by At

I have the following block of html:

<div class="product BLACKSHIRT">
<span class="displayPrice">£50</span>
</div>
<div class="product WHITESHIRT">
<span class="displayPrice">£40</span>
</div>
<div class="product GREENSHIRT">
<span class="displayPrice">£55</span>
</div>
<div class="product YELLOWSHIRT">
<span class="displayPrice">£50</span>
</div>
<div class="product BLACKJACKET">
<span class="displayPrice">£60</span>
</div>
<div class="product WHITESHORTS">
<span class="displayPrice">£20</span>
</div>
<div class="product BLACKTROUSERS">
<span class="displayPrice">£30</span>
</div>

What I would like to do is pick out each div has either "SHIRT" or "JACKET" as part of the class name, and then hooks out the value of the inner span - and adds 15 to the current value, so for example

<div class="product BLACKSHIRT">
<span class="displayPrice">£50</span>
</div>

becomes

<div class="product BLACKSHIRT">
<span class="displayPrice">£65</span>
</div>

Is this possible? I don't have any control over the existing html and am aware that the "£" needs to be stripped in order to make the value into a number.

1

There are 1 best solutions below

5
Barmar On BEST ANSWER

Use the Attribute Contains Selector *=.

$("[class*=SHIRT] .displayPrice, [class*=JACKET] .displayPrice").html((i, oldhtml) => '£' + (15 + parseFloat(oldhtml.substr(1))).toFixed(2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product BLACKSHIRT">
  <span class="displayPrice">£50</span>
</div>
<div class="product WHITESHIRT">
  <span class="displayPrice">£40</span>
</div>
<div class="product GREENSHIRT">
  <span class="displayPrice">£55</span>
</div>
<div class="product YELLOWSHIRT">
  <span class="displayPrice">£50</span>
</div>
<div class="product BLACKJACKET">
  <span class="displayPrice">£60</span>
</div>
<div class="product WHITESHORTS">
  <span class="displayPrice">£20</span>
</div>
<div class="product BLACKTROUSERS">
  <span class="displayPrice">£30</span>
</div>