Reputation: 12459
With Mootools, what's the cleanest way of setting an element's text without overwriting any child nodes?
I want to go from this
<div id="foo">
foo
<div id="bar">
bar
</div>
</div>
... to this
<div id="foo">
new improved foo
<div id="bar">
bar
</div>
</div>
I thought this would do it:
$('foo').set('text', 'new improved foo')
but that replaces the whole element contents, resulting in
<div id="foo">
new improved foo
</div>
(btw, this is identical to set('html', ...)
AFAICS. Is this a Mootools bug?)
Upvotes: 0
Views: 1596
Reputation: 17010
If text content is always the first thing inside your tags, you can try to get all children elements, edit text and then re-inject children later.
var myChildren = $('foo').getChildren().dispose();
$('foo').set('text', 'new improved foo');
$('foo').adopt(myChildren);
Demo here: http://jsfiddle.net/x2Vke/
Anyway, if you can edit your HTML code, I suggest you to wrap your text contents in some inline tag like <span>
and reference to it in order to replace text:
<div id="foo">
<span class="text-content">foo</span>
<div id="bar">
bar
</div>
</div>
Then you can simply do:
$('foo').getFirst('.text-content').set('text', 'new improved foo');
Demo: http://jsfiddle.net/hMNXN/
Upvotes: 6