Prototype Quick Tip

written by Tobie on May 22nd, 2007 @ 07:48 AM

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

  • Ash Searle
    Ash Searle says:

    It may be better to call String() instead of toString() – this copes with null and undefined without throwing an error:

    appendText: function(element, text) {
      element = $(element);
      element.appendChild(document.createTextNode(String(text)));
      return element;
    }

    Tue, May 22 at 09:43 AM

  • Mad Max
    Mad Max says:

    Can I add onClick using DOMBuilder? Something like:

    var row=new Element(‘tr2’,{ onclick:function(evt){...} }

    Wed, May 30 at 08:49 AM

Comments are closed