update(element[, newContent]) -> HTMLElement

Replaces the content of element with the provided newContent argument and returns element.

newContent can be plain text, an HTML snippet, or any JavaScript object which has a toString() method.

If it contains any <script> tags, these will be evaluated after element has been updated (Element.update internally calls String#evalScripts).

If no argument is provided, Element.update will simply clear element of its content.

Note that this method allows seamless content update of table related elements in Internet Explorer 6 and beyond.


<div id="fruits">carrot, eggplant and cucumber</div>

Passing a regular string:

$('fruits').update('kiwi, banana and apple');
// -> HTMLElement
// -> 'kiwi, banana and apple'

Clearing the element’s content:

// -> HTMLElement
// -> '' (an empty string)

And now inserting an HTML snippet:

$('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p>');
// -> HTMLElement
// -> '<p>Kiwi, banana <em>and</em> apple.</p>'

… with a <script> tag thrown in:

$('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p><script>alert("updated!")</script>');
// -> HTMLElement (and prints "updated!" in an alert dialog).
// -> '<p>Kiwi, banana <em>and</em> apple.</p>'

Relying on the toString() method:

// -> HTMLElement
// -> '123'

Finally, you can do some pretty funky stuff by defining your own toString() method on your custom objects:

var Fruit = Class.create();
Fruit.prototype = {
  initialize: function(fruit){
    this.fruit = fruit;
  toString: function(){
    return 'I am a fruit and my name is "' + this.fruit + '".'; 
var apple = new Fruit('apple');

// -> 'I am a fruit and my name is "apple".'