0

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

4 Answers 4

4

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

Alternatively, you could use this approach to replace tags:

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

1 Comment

According to this jsperf test (not quite the same approach but would probably yield similar results anyway) your approach is likely faster so it's probably best to stick with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.