CSSgallery.info

04 2008

A beginner’s mootools - select and create elements


In 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:

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 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’.

The creation of an element is done by declaration:

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

Let’s explain a little:

type - define 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:

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

As u 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.


Leave a Reply

« Submit yours web development on OS X »