30 Days of Mootools 1.2 Tutorials - Day 6 - Manipulating HTML

- Troy

Manipulating HTML DOM Elements with Mootools 1.2

If you haven’t already, be sure and check out the rest of the Mootools 1.2 tutorials in our 30 days series.

We have already looked at how to select elements within the DOM, how to create arrays, how to create functions, how to attach events to elements and today we are going go further into manipulating HMTL elements. With Mootools 1.2, you can add new elements into an html page, remove elements, and change any style or element parameters, all on the fly.

The Basics

.get();

This tool lets you retrieve element properties. Element properties are the various pieces that make up an html element, such as src, value, name, etc. Using .get(); is very simple:

//this will return the html tag (div, a, span...) of the element with the id "id_name"
$('id_name').get('tag');
<div id="body_wrap">
    <span id="id_name">Element</span> <!-- the above code would return "span" -->
</div>

You can use .get() to retrieve more than just html tags:

  • id
  • name
  • value
  • href
  • src
  • class (will return all classes if the element has multiple)
  • text (the text content of an element)
  • etc…

.set();

.set(); works just like .get();, except instead of getting a value, it sets a value. This is useful when combined with events and lets you change values after the page has loaded.

//this will set the href of #id_name to "http://www.google.com"
$('id_name').set('href', 'http://www.google.com');
<div id="body_wrap">
    <!-- the above code would change the href url to "http://www.google.com  -->
    <a id="id_name" href="http://www.yahoo.com">Search Engine</a>
</div>

.erase();

With .erase();, you can erase the value of an elements property. It works just like the previous two. Select your element, then choose which property you want to erase.

//this will erase the href value of #id_name
$('id_name').erase('href');
<div id="body_wrap">
    <!-- the above code would erase the href url  -->
    <a href="http://www.yahoo.com">Search Engine</a>
</div>

Moving Elements

.inject();

To move an existing element around the page, you can use .inject();. Like the other tools we have looked at, it’s very easy to use and gives you a lot of control over your user interface. To use .inject();, lets first set up a few elements within variables:

var elementA = $('elemA');
var elementB = $('elemB');
var elementC = $('elemC');

The above code places this html into variables, making it easy to manipulate with Mootools.

<div id="body_wrap">
    <div id="elemA">A</div>
    <div id="elemB">B</div>
    <div id="elemC">C</div>
</div>

Now, to change the order of the elements, we can use .inject one of four ways. We can inject to the:

  • bottom (default)
  • top
  • before
  • after

Bottom and top will place the injected element inside a selected element, in the top or bottom spot. Before and after on the other hand, will inject one element before or after another, but not inside.

So, lets change the order to A-C-B. Since we don’t need to inject an element inside another, we can use before or after.

//translates to:  inject element C before element B
elementC.inject(elementB, 'before'); 
 
//translates to:  inject element B after element C
elementB.inject(elementC, 'after');

Creating a New Element

new Element

You can use the “new Element” constructor to create a new html element. It’s very much like writing a regular html element, except we will adjust the syntax to make it play well with Mootools:

//first, you name a variable and declare a "new Element"
//then you define which type of element (div, a, span...)
var newElementVar = new Element('div', {
    //here you set all the element parameters
    'id': 'id_name',
    'text': 'I am a new div',
    'styles': {
        //here you set all the style parameters
        'width': '200px',
        'height': '200px',
        'background-color': '#eee',
        'float': 'left'
    }
});

Now that you have an element, you can inject it somewhere with the code we learned earlier. Let’s start with the following simple html:

<div id="body_wrap">
    <div id="content_id">Some div content</div>
</div>

Now, lets turn #content_id into a variable:

var bodyWrapVar = $('body_wrap');

Just like we learned before, we can inject the element we created into the current html:

//translates to, "inject newElementVar inside bodyWrapVar, in top position
newElementVar.inject(bodyWrapVar , 'top');

The html would end up looking like:

<div id="body_wrap">
    <!-- this element was injected to the inside-top -->
    <div id="id_name">I am a new div</div>
    <div id="content_id">Some div content</div>
</div>

Example

For this example, lets create a form that lets you add a new element to your html page. First, lets set up some inputs and a button.

<div id="body_wrap">
        ID:  <input id="id_input" name="id" />
        text:  <input id="text_input" name="text" />
        <button id="new_div">create a new div</button>
</div>

Now, lets build the Mootools JavaScript that will let this html form inject a new element into your page. First, let’s add a click event the button and create a function to contain our code:

var newDiv = function() {
    //we are going to put our "add a new element" code in here
};
 
window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});

The next thing we need to figure out is what kind of variables we are going to be dealing with. To use the data in the input forms, we need to .get(); it:

var idValue = $('id_input').get('value');
var textValue = $('text_input').get('value');

Now the variables above, idValue and textValue, contain the value of their respective input forms. Since we want to get the value of the input fields at the time the user clicks the “create a new div” button, we need to place the above code within the newDiv(); function. If we were to get(); the values outside of the function, we would get the values on load, not on click.

var newDiv = function() {
    var idValue = $('id_input').get('value');
    var textValue = $('text_input').get('value');
};
 
window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});

Next, we are going to need to grab our element that we want to inject the new div into:

var newDiv = function() {
    var idValue = $('id_input').get('value');
    var textValue = $('text_input').get('value');
    var bodyWrapVar = $('newElementContainer');
};
 
window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});

Since we have our input values, we can now create the new element:

var newDiv = function() {
    var idValue = $('id_input').get('value');
    var textValue = $('text_input').get('value');
    var bodyWrapVar = $('newElementContainer');
 
    var newElementVar = new Element('div', {
        //this sets the id to the value of the input by passing a variable
    	'id': idValue,
        //this sets the text to the value of the input by passing a variable
    	'html': textValue
    });
};
 
window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});

All we have left is to inject the new element into our page:

var newDiv = function() {
	var bodyWrapVar = $('newElementContainer');
	var idValue = $('id_input').get('value');
 
 
 
 
	var textValue = $('text_input').get('value');
 
	var newElementVar = new Element('div', {
    	        'id': idValue,
    	        'text': textValue
	});
 
        //translates to, "inject newElementVar inside-top of bodyWrapVar."
	newElementVar.inject(bodyWrapVar, 'top');
};
 
var removeDiv = function() {
        //this erases the inner html (which is everything inside of the div tags)
	$('newElementContainer').erase('html');
}
 
window.addEvent('domready', function() {
   $('new_div').addEvent('click', newDiv);
   $('remove_div').addEvent('click', removeDiv);
});

ID:

text:


(try putting “ilovemilk” as the id)

To Learn More…

Make sure to take some time with the Elements section within the Mootools docs:

  • Element contains most of what we talked about here and a lot more
  • Element.style gives you control over style properties (something we will dig into more in another tutorial)
  • Element.dimensions contains tools for dealing with position, coordinates and more

Tomorrow’s tutorial

30 Days of Mootools, Day 7 - Setting and Getting Style Properties

Tutorial Request or Questions

Now that we have had a chance to cover some of the basics, the tutorials are going to start to pick up. Feel free to drop a note with any suggestions, comments or questions. Thanks and I hope you find this useful.

Bookmark and Share

Comments (8) Trackbacks (3)
  1. reza


    hi . your tutorials are very practical. i used theme in my codes and i didn't see any tutorial like here. thank you and i hope that you continue this way.

    you can see our website and send me your opinion to my e-mial. (index is FULL javaScript)
  2. Tompa


    Thank you for these tutorials. As i just started to learn mootools i found them very practical and informative.
    Thanks again :)
  3. rama krishna


    hi... thanks for the tutorials.every property is being well explained with an example.

    thanks again
  4. Marx


    Thanks a lot for your tutorials! It has helped me immensely these last days. Will continue reading the whole series, a must-read.
  5. George


    Thanks for this great tutorial, but I have a problem. I can´t change id of a div. Is it possible?

    $('2').set('id', '1');

    What is wrong??
  6. Opera9good


    $('2').set('id', '1');

    specification says that the every html element's id must begin with letter (or maybe _ ?),
    it is like in PHP: variables' names cannt begin with number
  7. Rahul


    Thanks for these lessons. It may just be that after reading the clientside tutorials and MooTools essentials, I'm finally getting it after reading this or just that your use of practical examples with actual functioning examples really makes the points clear.

    Thanks for making this. I'm looking forward to reading the remaining lessons.
  8. kastiuz


    Great job!, go on! ;D


Leave a Reply