ic3
ic3

Reputation: 7690

Jquery replacing text inside html

Is there a more elegant way replacing a text inside an html element than :

$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );

Upvotes: 2

Views: 180

Answers (4)

Amit Gupta
Amit Gupta

Reputation: 577

you can try

e1.html(function(i,oldHtml){
     return oldhtml.replace("something", "something new");
}

its different but not sure about elegance.

Upvotes: 0

Naveed
Naveed

Reputation: 42143

If I understand:

oldText = $('#myDiv').html();
$('#myDiv').html( oldText.replace('something','something new') );

http://jsfiddle.net/wmgBN/

Upvotes: 1

Ahmed Magdy
Ahmed Magdy

Reputation: 6050

there is nothing more elegant than the example you wrote! Check this exmple http://blog.chapagain.com.np/jquery-how-to-replace-string-div-content-and-image-src/

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

$('#myDiv').html(function(index, oldhtml) {
    return oldhtml.replace('something', 'something new');
});

Upvotes: 6

Related Questions