Reputation: 13
I have the html below:
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Batman Graphic Tee - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $14.99</p>
<p class="pt_5 oos">Superman Flying Graphic Tee</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Spiderman vs Venom Hoodie - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $9.99</p>
<p class="pt_5 oos">Wolverine vs Magento Tank</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Hulk vs Thanos - Out Of Stock</p>
</div>
I'm using the function below to update the text in the 'P' tag with class 'oos_msg' IF a condition is met.
$('.oos').text(function() {
if ($('.oos:contains("Out Of Stock")')) {
$('.oos_msg').html('Out Of Stock');
}
})
The problem I'm having is that it's updating every single 'P' tag, which has a class oos_msg, what am I doing wrong?
JSFiddle link: https://jsfiddle.net/jingz/3r5L84e6/17/
Upvotes: 1
Views: 38
Reputation: 42304
There are two problems:
$('.oos_msg')
selector selects all of the .oos_msg
elements, so all of them will have their .html()
updated.$('.oos:contains()')
also has the same problem -- if any of them contain that text, then the conditional will be triggered.To correct this, you can use $(this)
to only target the current element that you're looping over, in conjunction with .is()
and the :contains
selector to handle the contained text.
This can be seen in the following:
$('.oos').text(function() {
if ($(this).is(':contains("Out Of Stock")'))
$(this).prev().html('Out Of Stock');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Batman Graphic Tee - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Superman Flying Graphic Tee</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Spiderman vs Venom Hoodie - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Wolverine vs Magento Tank</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Hulk vs Thanos - Out Of Stock</p>
</div>
Upvotes: 5