user3169890
user3169890

Reputation: 13

Replacing specific text within elements without having it affect elements with same class

The code below works for the first h3, but it also changes the second so I end up with both saying 'Country Filter', I need the first h3 to say 'Country Filter' and the second to say 'State Filter'. Any help, without altering the html, would be appreciated. thanks.

Here is the html:

<h3>  
    <span class="label">Browse by</span> 
    <span class="location">Country</span> 
</h3>
<h3>  
    <span class="label">Browse by</span> 
    <span class="location">City</span> 
</h3>

Here is the jquery:

if ($(".location:contains('Country')")) {
    $(".label").text(function () {
        return $(this).text().replace("Browse by", "Country");
    });
    $(".location").text(function () {
        return $(this).text().replace("Country", "Filter");
    });
}

if ($(".location:contains('City')")) {
    $(".label").text(function () {
        return $(this).text().replace("Browse by", "State");
    });
    $(".location").text(function () {
        return $(this).text().replace("City", "Filter");
    });
}

Upvotes: 0

Views: 30

Answers (3)

Marcel
Marcel

Reputation: 1191

Much simpler:

$(".location:contains('Country')").siblings().text("Country");
$(".location:contains('City')").siblings().text("State");
$(".location").text("Filter");

Why are you targeting the spans by the text they contain? Why would you ever need to change the contents like this? Just curious.

Upvotes: 0

cafonso
cafonso

Reputation: 909

Identify the outer h3 tag using an id

<h3 id="country">
    <span class="label">Browse by</span> 
    <span class="location">Country</span> 
</h3>

Then update your selector accordingly:

$("#country .label").text(function () {
    return $(this).text().replace("Browse by", "Country");
});

Upvotes: 0

Satpal
Satpal

Reputation: 133403

Use

//Find location that contains text
var countrylocation = $(".location:contains('Country')"); 
//As label is prev element, Here you can also use siblings
countrylocation.prev(".label").text(function () {
    return $(this).text().replace("Browse by", "Country");
});
countrylocation.text(function () {
    return $(this).text().replace("Country", "Filter");
});

var citylocation = $(".location:contains('City')");
citylocation.prev(".label").text(function () {
    return $(this).text().replace("Browse by", "State");
});
citylocation.text(function () {
    return $(this).text().replace("City", "Filter");
});

References:

  1. .siblings()
  2. .prev()

Upvotes: 2

Related Questions