Pabs123 Pabs123 - 7 months ago 8
Javascript Question

jQuery selector for varying HTML structure

I'm working with a page which displays a product's price. Normally it looks like this:

<span id="priceText">
$26.94
</span>


When the item is on sale, it looks like this:

<span id="priceText">
<strike>$26.94</strike>
<span class="salePrice">$25.00</span>
</span>


I have a generic function which extracts the price from any page like so:

var getPrice = function(price_id) {
return jQuery(price_id).text();
};


Where
price_id
is the id of the element which contains the price.

As is plainly obvious, this will not work with the above structure since the "sale" version will return both $26.94 and $25.00 if I set price_id to
priceText


I do not have control over the html on the product's page, so I can't change the structure. I need to use the
getPrice
function on other pages which do not have this HTML structure, so I also want to avoid changing it.

What I am looking for is some sort of jQuery selector which will return $25.00 if the item is on sale, or $26.94 if it isn't. Something like "return all text inside of
priceText
NOT in a strike tag"

I currently have a custom snippet which does the following:

jQuery('#priceText .salePrice').length ? jQuery('#priceText .salePrice').text() : jQuery('#priceText strike').text()


However I want to avoid custom lines of code like this. I think this may not be possible using only jQuery selectors but I'm hoping someone proves me wrong!

GG. GG.
Answer

You can use a multiple selector.

jQuery('#priceText .salePrice, #priceText:not(:has(.salePrice))').text()

DEMO

Comments