Pabs123
Pabs123

Reputation: 3435

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!

Upvotes: 3

Views: 47

Answers (2)

GG.
GG.

Reputation: 21854

You can use a multiple selector.

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

DEMO

Upvotes: 3

Diego Polido Santana
Diego Polido Santana

Reputation: 1435

Maybe you could reduce your condition by this:

($('#priceText .salePrice') || $('#priceText strike')).text()

Upvotes: 1

Related Questions