Reputation: 580
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
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
Reputation: 23859
Your if
expression is a bit odd. The expression will always evaluate to true
if both of the below are true:
h4
that contains the text Topic
. Because in that case, $("H4:contains('Topic')")
will return a truthy value.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 h4
s 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