I have a list of items, each with a button and a price. I am able to find the button that says "choose options", and then apply a change to another div, however, it changes that div for all <li>
s, and not just the one where the button text occurs. How do I contain the change to only the relevant <li>
?
if ($('ul li:contains("Choose Options")')) {
$(".p-price").prepend("STARTING AT: ");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<em class="p-price">$1.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Add To Cart</a>
</div>
</li>
<li>
<em class="p-price">$4.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Choose Options</a>
</div>
</li>
<li>
<em class="p-price">$5.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Add To Cart</a>
</div>
</li>
</ul>
<script>
</script>
The Script above does find the "choose options" text. But then it adds "Starting At: " to all .p-price
instances. How do I have it only change the .p-price
in the same <li>
? So that the <li>
s that have "add to cart" button, don't get the text insert before the price?
I've read about .each()
, return false
, and looping, but not sure If I'm barking up the correct tree, as I've tried various code iterations that fail horribly, but when it comes to this specific if contains, change another div, I cannot find anything that comes close.
No if
needed: just prepend the text to any matching elements that may exist:
$('li:contains("Choose Options") .p-price').
prepend("STARTING AT: ");
$('li:contains("Choose Options") .p-price').
prepend("STARTING AT: ");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<em class="p-price">$1.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Add To Cart</a>
</div>
</li>
<li>
<em class="p-price">$4.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Choose Options</a>
</div>
</li>
<li>
<em class="p-price">$5.95</em>
<div class="ProductActionAdd">
<a href="" class="btn">Add To Cart</a>
</div>
</li>
</ul>