Reputation: 1554
I'm confused about the possibilities of setting the text
attribute, and the difference with setting html
. Basically, I have a paragraph with an image in it:
<p id="test">Title <img src="/someimage.jpg" /></p>
What I want to do, is change 'Title' to something else. So what I do (using MooTools):
$('test').set('text', 'Different title');
However, this just replaces the entire contents of the paragraph element, stripping the image element, as shown here: http://jsfiddle.net/4vhtR/1/
I would've expected this to just change the text, the actual text, and not any HTML elements that are contained. Now it just seems the same as using set('html', 'Different title')
.
Why does it work this way? And how can I only really change the text, without resorting to wrapping the text in a <span>
or cloning and putting back the image with JS, which would just complicate it?
Upvotes: 0
Views: 532
Reputation: 26165
The correct way to do things is via text nodes. https://developer.mozilla.org/en-US/docs/DOM/Node.nodeValue
Element.implement({
getTextNodes: function(){
return Array.filter(this.childNodes, function(el){
return el.nodeType == 3;
});
}
});
var textNodes = $('test').getTextNodes();
textNodes[0].nodeValue = 'Hi there';
http://jsfiddle.net/dimitar/4vhtR/4/
this will return a collection of all textNodes you can update the value of so you can reference any bit of text you like.
Upvotes: 3