2

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
1
  • 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. Commented Jun 2, 2011 at 9:05

4 Answers 4

6
$('#myDiv').html(function(index, oldhtml) {
 return oldhtml.replace('something', 'something new');
});
answered Jun 2, 2011 at 8:41
Sign up to request clarification or add additional context in comments.

7 Comments

Why are you passing in the index?
@DOK To be able to set the 2nd argument I'd imagine
@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).
Is this method quicker (or using less resourced) ?
@icCube, yes, because the selector is evaluated only once.
|
1

If I understand:

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

http://jsfiddle.net/wmgBN/

answered Jun 2, 2011 at 8:41

2 Comments

is replacing in the html all "something" with "something new", not putting "something new" as the new html content
@icCube: is it what your are looking for ?
0

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

1 Comment

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
0

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
answered Jun 2, 2011 at 8:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.