update
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 the new content contains any inline <script>
tags (script tags containing the code directly, rather than referring to a separate file), update
will extract them and evaluate them via String#evalScripts
after updating the content. See String#evalScripts
for details.
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.
Examples
<div id="fruits">carrot, eggplant and cucumber</div>
Passing a regular string:
$('fruits').update('kiwi, banana and apple');
// -> HTMLElement
$('fruits').innerHTML
// -> 'kiwi, banana and apple'
Clearing the element’s content:
$('fruits').update();
// -> HTMLElement
$('fruits').innerHTML;
// -> '' (an empty string)
And now inserting an HTML snippet:
$('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p>');
// -> HTMLElement
$('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>');
// -> HTMLElement (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);
// -> HTMLElement
$('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();
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');
$('fruits').update(apple);
$('fruits').innerHTML;
// -> 'I am a fruit and my name is "apple".'