Jack Pilowsky
Jack Pilowsky

Reputation: 2303

Targetting text but not targeting sibling element with CSS

In the example below, I'm trying to target the "$59.00"

<div class="ProductPriceRating">
    <em>
        <strike class="RetailPriceValue">$69.00</strike> 
        $59.00
    </em>
</div>

I'm a little stuck on this.

Upvotes: 1

Views: 69

Answers (3)

Hashem Qolami
Hashem Qolami

Reputation: 99494

How about jQuery? Can I target it with Jquery and then wrap an element around it?

Well, you could select the text node and add a wrapper as follows:

$('.ProductPriceRating')
  .find("em")
  .contents()
  .filter(function() {
    return this.nodeType === 3; // filter the text node
  }).wrap("<span></span>");

WORKING DEMO

CSS:

.ProductPriceRating span {
    color: red;
}

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157334

You cannot do this unless you are willing to change your DOM or you are willing to override.

So either you need to wrap the text using a span element and than target like

div.ProductPriceRating > em > span {

}

Else if you cannot change the DOM than you need to use two selectors, where first will apply the style to em and the next one will override that using strike

Demo

div.ProductPriceRating > em {
    color: red;
}

div.ProductPriceRating > em > strike {
    color: black;
}

The other way you can use is :not but if you are using color than inheritance will cause you problems

Demo

div.ProductPriceRating em:not(.RetailPriceValue) {
    background: red;
}

As you commented, you are willing to go with jQuery, than here you go, we are wrapping the node using jQuery..

$(".ProductPriceRating em").contents().filter(function() {
    return this.nodeType != 1; //or return this.nodeType == 3;  <-- Preferable 
}).wrap("<span></span>");

Demo

Upvotes: 3

Ashish Kumar
Ashish Kumar

Reputation: 3039

It's not possible to select specific text in CSS, but in your case you can do it overwriting the CSS property.

Here is an example:

.ProductPriceRating em{font-weight:700; font-size:20px; color:darkgreen}
.ProductPriceRating em .RetailPriceValue{color:#AAA; font-size:11px}

Working Demo

Addition:

As you mentioned in the comment above, that you want to do it with jQuery like wrapping up the text with an element. here is the example for that:

$(".ProductPriceRating").each(function(c, obj){
    obj = $(obj).find(">em"),
    retailPrice = obj.find(".RetailPriceValue").detach(),
    newNode = $("<b/>").text($.trim($(obj).text()));

    obj.html(newNode).prepend(retailPrice);
});

jQuery Demo

See the CSS there, both are separate working...

Upvotes: 0

Related Questions