Creating a DIV with a border on it

Before injecting any elements to our HTML DOM we should run HTML validation on our page. Valid HTML is crucial to having consistent, cross-browser results.

How to do it...

There is a great, artistic beauty to a syntax so simple as the constructor for the Element class. The first, mandatory parameter is the tag name. In this example we pass div in order to create a DIV tag in memory, not on the page...yet. The second parameter to the constructor is an object of properties to assign to the in-memory element.

<form action="javascript:" method="get">
<span id="my_error"></span>
<input id="submit" type="button" value="Submit Form"/>
</form>
<script type="text/javascript">
$('submit').addEvent('click', function() {
// the element constructor has a simple syntax
my_error = new Element('div', {
'id': 'my_error',
'text': 'Error!',
'style': 'border: 1px solid #F00; width:200px;'
});
// use element.replaces() to switch the span with a div
my_error.replaces($('my_error'));
// remove the error after a specified number of mseconds
setTimeout("$('my_error').set({'text':'','style':''})",3000);
});
</script>

After pressing the submit button we should see this injection for three seconds:

How it works...

In the second argument, where we pass an object of key/value properties to be assigned to the new element, we must pass the ID attribute or we may have trouble accessing the element later. For instance, when we remove the error we use the ID element along with a raw JavaScript, built-in function, setTimeout().

There's more...

The Element method replaces() is used on an element, whether in-memory or on a page. Pass the element with which the replacement should happen. We can remember it this way: my_incoming_element.replaces(my_outgoiing_element) or more concisely, keeper.replaces(loser), and, yes, it is quite semantically correct! Just remember "Keeper Fires, Loser Passes".