A beginner’s mootools – select and create elements

In a previous tutorial we learned how to add events to elements in webpage. In this one we will learn how to select elements – or better said how to access an element from page, and how to create new elements in page.

In mootools we have two functions that select an element:

the function $ – this is equivalent of document.getElementById and returns the object selected.

If we have an element with id = ‘my_element’, the expression

$('my_element')

will return that element, then we will be able to manipulate it.
And the function $$ – this one allows you to select multiple objects, and return an array with selected objects.
$$(‘a’) will return all the ‘a’ elements in document.
A nice trick done by $$ is that you are able to select all the elements with same class:

$$('.my_class')

will select all the elements in page that have class=’my_class’.
To create an element you will declare this:

var my_element =  new Element( type, { options }) ;

Let’s explain a little:
type – defines the type of the element, for example img, li, input, div, etc…
options – this lets you specify at the moment of creation the attributes the new element has.
options is not mandatory, the equivalent html code being – let’s say for div:

<div></div>

An example on how to create an element with Mootools:

var my_img = new Element ( 'img' , { 'src' : 'aa.jpg' , 'style' :  'width:200px; border:3px solid red' });

As u can see, we create an img element and we set the src as aa.jpg and the style as above.
Please note the way options are declared:

{attribute:value, attribute:value}

so pairs of attribute:value coma separated.
Ok, now we have the element my_img, but is not yet viewable. The new created element exist in browsers memory, but is not inserted yet in page. For this we need to use one of:

injectBefore(element);
injectAfter(element);
injectInside(element);
injectTop(element) ;

Remember the selectors we explained at the beginning of this tutorial?
The element object is exactly an object select using $, or created previously,using new Element();
What each inject does?
injectBefore( element ); - injects the new created element just before the passed element;

injectAfter(element); – injects the new created element just after the passed element.
injectInside(element); – injects the new created element inside the passed element, at the bottom. Be carefull you have to pass an element that support subelements – you cannot insert an ul in an img for example.
injectTop(element); – injects the new created element inside the passed element but at the top.
Take a look at the example page , and in source to see practical implementation.