Pabs123 Pabs123 - 6 months ago 6x
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">

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

<span id="priceText">
<span class="salePrice">$25.00</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();

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

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
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
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!


You can use a multiple selector.

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