Prototype Quick Tip
Living on the edge and using Prototype’s latest DOM Builder ? Feeling a bit dirty doing the following:
new Element('div').update('some text...');
// --> <div>some text...</div>
Here’s a quick solution (using Element.addMethods) to fully dwell in complete web-standardness:
Element.addMethods({
appendText: function(element, text) {
element = $(element);
text = String.interpret(text);
element.appendChild(document.createTextNode(text));
return element;
}
});
Best part is that it lets you append anything, as long as the text argument has a toString method (thanks to Ash Searle for suggesting a better handling of null and undefined):
new Element('div').appendText('Some more text.');
// --> <div>Some more text.</div>
new Element('div').appendText(123);
// --> <div>123</div>
Comments
-
It may be better to call
String()instead oftoString()– this copes withnullandundefinedwithout throwing an error:appendText: function(element, text) { element = $(element); element.appendChild(document.createTextNode(String(text))); return element; }Tue, May 22 at 09:43 AM
-
Can I add onClick using DOMBuilder? Something like:
var row=new Element(‘tr2’,{ onclick:function(evt){...} }
Wed, May 30 at 08:49 AM