MultiDev
MultiDev

Reputation: 10649

Using jQuery to replace a specific part of HTML

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:

http://jsfiddle.net/2pBcj/

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

Answers (4)

sroes
sroes

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>')
);

http://jsfiddle.net/2pBcj/3/

Personally i'd go for the following approach though:

$(this).find('em').each(function() {
    $(this).replaceWith($('<strong />').html($(this).html()));
});

http://jsfiddle.net/PTf42/

Upvotes: 4

Josh Davenport-Smith
Josh Davenport-Smith

Reputation: 5511

Alternatively, you could use this approach to replace tags:

$(this).find('em').each(function() { 
  $(this).replaceWith($('<strong>' + this.innerHTML + '</strong>'));
});

Upvotes: 0

Luis Masuelli
Luis Masuelli

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

MDiesel
MDiesel

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

Related Questions