Reputation: 10649
I am trying to find a specific part of HTML code, and replace it with another using jQuery. I have replicated the issue as simple as possible with a jsfiddle:
In the example, I am trying to change the font from italic to bold when the mouse exits the DOM. I am using replace
, but it is not working. I don't know what to change.
$(this).html().replace('<em>', '<strong>').replace('</em>', '</strong>');
Upvotes: 0
Views: 50
Reputation: 15053
You're getting and replacing the html, but not doing anything with it at the end. Try this:
$(this).html(
$(this).html().replace('<em>', '<strong>').replace('</em>', '</strong>')
);
Personally i'd go for the following approach though:
$(this).find('em').each(function() {
$(this).replaceWith($('<strong />').html($(this).html()));
});
Upvotes: 4
Reputation: 5511
Alternatively, you could use this approach to replace tags:
$(this).find('em').each(function() {
$(this).replaceWith($('<strong>' + this.innerHTML + '</strong>'));
});
Upvotes: 0
Reputation: 12333
replace
is not an in-place method, and even being so, it doesn't mean that .html(content) will be called. If replace was an inplace call, the returned string would be changed, but not the true, inner, original html.
Consider you are doing this in one step:
var str_ = $(this).html();
str_.replace(...).replace(...);
As you see, the html content would not be modified.
Bit it is even WORSE since the replace
method is not inplace, so str_
and str_.replace(...).replace(...)
would have different objects.
you MUST wrap your
$(this).html().replace('<em>', '<strong>').replace('</em>', '</strong>');
inside a $(this).html(...) call:
$(this).html($(this).html().replace('<em>', '<strong>').replace('</em>', '</strong>'));
Upvotes: 0
Reputation: 2667
The .html() method and subsequent .replace() methods are returning a string. If you wanted to replace the html with the string you would need to set $(this).html() with the updated string.
var updatedHtml = $(this).html().replace('<em>', '<strong>').replace('</em>', '</strong>');
$(this).html(updatedHtml);
Upvotes: 1