class method Element.update

View source on GitHub →

Element.update(element[, newContent]) → Element

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

newContent may be in any of these forms: - String: A string of HTML to be parsed and rendered - Element: An Element instance to insert - ...any object with a toElement method: The method is called and the resulting element used - ...any object with a toHTML method: The method is called and the resulting HTML string is parsed and rendered

If newContent is omitted, the element's content is blanked out (i.e., replaced with an empty string).

If newContent is a string and contains one or more inline <script> tags, the scripts are scheduled to be evaluated after a very brief pause (using Function#defer) to allow the browser to finish updating the DOM. Note that the scripts are evaluated in the scope of String#evalScripts, not in the global scope, which has important ramifications for your vars and functions. See String#evalScripts for details.

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

Any nodes replaced with Element.update will first have event listeners unregistered and storage keys removed. This frees up memory and prevents leaks in certain versions of Internet Explorer. (See Element.purge).

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

Passing a regular string:

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

Clearing the element's content:

$('fruits').update();
// -> Element
$('fruits').innerHTML;
// -> '' (an empty string)

And now inserting an HTML snippet:

$('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p>');
// -> Element
$('fruits').innerHTML;
// -> '<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>');
// -> Element (and prints "updated!" in an alert dialog).
$('fruits').innerHTML;
// -> '<p>Kiwi, banana <em>and</em> apple.</p>'

Relying on the toString() method:

$('fruits').update(123);
// -> Element
$('fruits').innerHTML;
// -> '123'

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

var Fruit = Class.create({
  initialize: function(fruit){
    this.fruit = fruit;
  },
  toString: function(){
    return 'I am a fruit and my name is "' + this.fruit + '".';
  }
});
var apple = new Fruit('apple');
 $('fruits').update(apple);
$('fruits').innerHTML;
// -> 'I am a fruit and my name is "apple".'

This method can be called either as an instance method or as a generic method. If calling as a generic, pass the instance in as the first argument.