Finding an element by its ID attribute

This cross-browser method allows us to quickly get a "handle" on our HTML element.

How to do it...

If we imagined a world where we could grab an element with a simple and easy-to-remember syntax just by sending the element's ID attribute, we would be dreaming of MooTools.

<script type="text/javascript"
src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger"
style="width:100px; height:100px;
border:1px solid #BEBEBE;
line-height:50px; text-align:center;">You Found Me!</div> <noscript>JavaScript is disabled.</noscript>

Tip

Always include the NOSCRIPT tag, which is omitted going forward only to save space.

<script type="text/javascript">
// raw javascript's familiar method, not cross-browser use
// var my_element = document.getElementByID('my_target');
// MooTools uses the $ object to grab elements by ID
var my_element = $('my_trigger');
var my_element_text = my_element.get('text');
alert(my_element_text);
</script>

Tip

Always include the closing BODY and HTML tags. Also omitted going forward.

 </body> </html>

How it works...

When we use raw JavaScript to get a handle on an element, we either depend on the browser to match our code, or we have to write a mess of browser compatibility to be sure that our user has a browser that supports the JavaScript implementation that we are writing for. MooTools abstracts that cross-browser nightmare and gives us the dollar object $(), an alias for document.id().

Note

Starting with version 1.2, MooTools began to use document.id() to grab elements by ID. This allows MooTools to play nice with other frameworks that extend using the dollar syntax. When using multiple frameworks, do not use the $() alias for document.id().

Pass the dollar or document.id() object the ID for the element to grab, and the object returned is a MooTools-extended object ready to do our bidding through Element methods.

In this example, we use the method get(), which takes a single argument, the property of the object to return. We then alert the var my_element_text to the screen using the raw JavaScript alert() function.

There's more...

This recipe can be easily recreated with a single, easy-to-understand one-liner:

alert($('my_trigger').get('text'));