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.
This is an old question but you can make a simple function like this to make your life easier:
Example:
Usage:
Just wrap the text you want to change in a span with a class to select.
Doesn't necessarily answer your question I know, but, probably a better coding practice. Keep things clean and simple
Voilà!
Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.
In Javascript, the
childNodes
property gives you all the child nodes of an element, including text nodes.So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this HTML:
You could do this:
Of course, you can still use jQuery to select the
<div>
in the first place (i.e.var your_div = $('your_div').get(0);
).This changes only the first textnode
Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin: