Andy Levesque
Andy Levesque

Reputation: 580

jQuery if statement to find and replace certain header text is replacing all headers

I'm trying to identify a certain h4 tag that contains certain text and class (it unfortunately does not have an id) and then replace that text. I have the following if statement, but when an h4 matches true for this if statement, it replaces all h4 tags on the page instead of just the one that rang true.

My challenge is that I can only implement this via global jQuery. Is that my downfall?

if ($("H4:contains('Topic')") && $('H4').hasClass('boxHeaderTitle')) {
    $('h4').text('Posts');
}

Upvotes: 0

Views: 135

Answers (2)

Ollie Brooke
Ollie Brooke

Reputation: 62

Try

if ($("H4:contains('Topic')") && $('H4').hasClass('boxHeaderTitle')) {
$(this).html('Posts');
}

or

$("H4.boxHeaderTitle:contains('Topic')").each(function(){
$(this).html('Posts');
});

Upvotes: 0

31piy
31piy

Reputation: 23859

Your if expression is a bit odd. The expression will always evaluate to true if both of the below are true:

  • there is at least one h4 that contains the text Topic. Because in that case, $("H4:contains('Topic')") will return a truthy value.
  • there is at least one h4 that has the class boxHeaderTitle assigned to it. Because in that case, $('H4').hasClass('boxHeaderTitle') will return a truthy value.

The catch is that in the body of if, you're setting the text of all the h4s to Posts.

The correct approach may be:

var heading = $("H4:contains('Topic')");

if ( heading.hasClass('boxHeaderTitle')) {
    heading.text('Posts');
}

I assume that you want to change the text of an h4 which contains Topic and also has the class boxHeaderTitle. Alternatively, you can altogether try a different approach:

$("H4.boxHeaderTitle:contains('Topic')").text('Posts');

The above works for multiple such tags as well.

Upvotes: 2

Related Questions