Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  121] [ 2]  / answers: 1 / hits: 97565  / 14 Years ago, fri, november 5, 2010, 12:00:00

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.


More From » html

 Answers
269

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:



<div id=your_div>
**text to change**
<p>
text that should not change
</p>
<p>
text that should not change
</p>
</div>


You could do this:



var your_div = document.getElementById('your_div');

var text_to_change = your_div.childNodes[0];

text_to_change.nodeValue = 'new text';


Of course, you can still use jQuery to select the <div> in the first place (i.e. var your_div = $('your_div').get(0);).


[#95065] Wednesday, November 3, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
iliana

Total Points: 246
Total Questions: 109
Total Answers: 82

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;