Reputation: 687
I need to replace a specific character for all elements whose class is the same with jQuery. Consider this html code:
<div class="product-name">
<h1>Apple®</h1>
</div>
<div class="product-name">
<h2>iPhone®</h2>
</div>
<div class="product-name">
<h3>iPhone 5S®</h3>
</div>
I need to replace all the ® charactesr with superscript tags with this code:
$('.product-name').html(
$('.product-name').html().replace(/®/gi, '<sup>®</sup>')
);
However, this code will replace the first occurrence only. For the second and beyond occurrences, it'll replace the whole product names with the first product name including the h1 tags.
How can I replace just the ® characters without changing the other characters and tags?
Upvotes: 5
Views: 403
Reputation: 1071
Try
$('.product-name').html().split("®").join('<sup>®</sup>');
For a more complete answer,
var body = $("body").html().split('®').join('<sup>®</sup>');
$("body").html(body);
Upvotes: 1
Reputation: 318352
You can use the callback in html()
to return the value to each element in the collection
$('.product-name').html(function(_, html) {
return html.replace(/®/gi, '<sup>®</sup>')
});
Upvotes: 4