I'd like to update element's text dynamically:
<div>
**text to change**
<someChild>
text that should not change
</someChild>
<someChild>
text that should not change
</someChild>
</div>
I'm new to jQuery, so this task seems to be quite challenging for me. Could someone point me to a function/selector to use?
If it is possible, I'd like to do it without adding a new container for the text I need to change.
For the specific case you mentioned:
... this is very easy:
You don't state how you want to generalize this. If, say, you want to change the text of the first text node within the
<div>
, you could do something like this:I think you're looking for .prependTo().
http://api.jquery.com/prependTo/
Update 2018
Since this is a pretty popular answer I decided to update and beautify it a little by adding the textnode selector to jQuery as a plugin.
In the snippet below you can see that I define a new jQuery function that gets all (and only) the textNodes. You can chain of this function as well with for example the
first()
function. I do a trim on the text node and check if it's not empty after the trim because spaces, tabs, new lines, etc. are also recognized as text nodes. If you need those nodes too then simple remove that from the if statement in the jQuery function.I added an example how to replace first text node and how to replace all text nodes.
This approach makes it easier to read the code and easier to use it multiple times and with different purposes.
The Update 2017 (adrach) should still work as well if you prefer that.
Update 2017 (adrach):
It looks like several things changed since this was posted. Here is an updated version
Original answer (Not working for current versions)
Source: http://api.jquery.com/contents/
See In action
Markup :
Simple answer:
Here is yet another method : http://jsfiddle.net/qYUBp/7/
HTML
JQUERY