Sanjeev Kumar
Sanjeev Kumar

Reputation: 3163

Find words and replace with tag wihtin div jQuery

I have a div with some text and I am trying to replace that text with a html tag using jQuery but, its replacing tag as text not as html tag

following is the html structure

<h3>Rs.1410 / 30 Tablet(s) </h3>

JS which I tried is

$("h3").text(function () {
    return $(this).text().replace("Rs.", "<i class='fa fa-inr'></i>"); 
});

If I try .html() then its replacing all the content within that div which I don't want. Can anybody please suggest

thanks

Upvotes: 0

Views: 68

Answers (3)

Sy Dy
Sy Dy

Reputation: 116

I would try something like this:

var text = $('h3').html().replace("Rs.", "<i class='fa fa-inr'></i>");
$('h3').html(text);

So basically, you are getting the h3 element, calling .html() to get its entire html contents, using replace as you already have and assigning the whole thing to a variable, and then subbing that variable in to another call to .html() to replace the existing HTML inside the h3 tag.

Upvotes: 0

Mahi
Mahi

Reputation: 1727

no need to use function

$("h3").html(
     $("h3").text().replace("Rs.", "<i class='fa fa-inr'></i>")); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Rs.1410 / 30 Tablet(s) </h3>

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68665

Use the html() function instead of text()

$("h3").html(function () {
    return $(this).text().replace("Rs.", "<i class='fa fa-inr'></i>"); 
});

From the documentation

A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.

Upvotes: 4

Related Questions