Sachin
Sachin

Reputation: 15

change span text using jquery based on parent element class

I checked through the forum but didn't find the solution for my problem. I am adding a class on an element based on the img src value. If img src contains 'amazon' a class is added to closest li element and based on that li element i'm changing text of a span. Till here everything is fine, after this I want to change the text of span whose parent li element doesn't have that class name. I can't figure out the solution for it. Here is my code.

<script>
jQuery(document).ready(function(){
    var select = 'img[src*="images-amazon.com"]';  
    jQuery(select).closest("li").addClass("sac-amazon");  

    var cls = jQuery("li.sac-amazon");
    var currency = jQuery("span.woocommerce-Price-currencySymbol");

    if(cls){
        currency.text("US $");
    }else if(!cls){
        currency.text("SG $");
    }   

});
</script>

Upvotes: 0

Views: 1133

Answers (2)

nimsrules
nimsrules

Reputation: 2064

Try this (replace 'New Text' with the string of your choice):

jQuery('ul li').each(function(){
  var t = jQuery(this);
  if(!t.hasClass('sac-amazon')){
    t.text('New text');
  }
});

Upvotes: 1

Satpal
Satpal

Reputation: 133403

I want to change the text of span whose parent li element doesn't have that class name

You need to target the child span only. use :not() selector to target li not having the class then use descendant selector

jQuery("li.sac-amazon span.woocommerce-Price-currencySymbol").text("US $");
jQuery("li:not(.sac-amazon) span.woocommerce-Price-currencySymbol").text("SG $");

Upvotes: 2

Related Questions