Is there a more elegant way replacing a text inside an html element than :
$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );
asked Jun 2, 2011 at 8:39
ic3
7,74015 gold badges73 silver badges123 bronze badges
-
For anyone who misses the point here (as I did), we want to replace only part of the text, not all of it. It would have been helpful to show the complete text before and after.DOK– DOK2011年06月02日 09:05:26 +00:00Commented Jun 2, 2011 at 9:05
4 Answers 4
$('#myDiv').html(function(index, oldhtml) {
return oldhtml.replace('something', 'something new');
});
answered Jun 2, 2011 at 8:41
Darin Dimitrov
1.0m277 gold badges3.3k silver badges3k bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
DOK
Why are you passing in the index?
Phil
@DOK To be able to set the 2nd argument I'd imagine
Darin Dimitrov
@DOK, because that's how the signature of the callback is defined. It represents the index in the matched set of elements by the selector. In this case it will always be the same as an id selector was used (which is supposed to be unique).
ic3
Is this method quicker (or using less resourced) ?
Darin Dimitrov
@icCube, yes, because the selector is evaluated only once.
|
If I understand:
oldText = $('#myDiv').html();
$('#myDiv').html( oldText.replace('something','something new') );
answered Jun 2, 2011 at 8:41
Naveed
42.3k31 gold badges101 silver badges132 bronze badges
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/
answered Jun 2, 2011 at 8:44
Ahmed Magdy
6,0888 gold badges46 silver badges77 bronze badges
1 Comment
Eugene
I think example of Darin Dimitrov is better (I can't judge the elegance). It's better because there is only one call of .html() method, but in author's example (and example from your link) there are 2 calls of .html() method
you can try
e1.html(function(i,oldHtml){
return oldhtml.replace("something", "something new");
}
its different but not sure about elegance.
ic3
7,74015 gold badges73 silver badges123 bronze badges
Comments
default