Javascript Tip #001: YUI DOM

This series is intended to help you get started with using YUI as well as various tips I've learned over the years to help you with your javascript coding.

Not many folks know that the YUI libraries are now hosted online for anyone to use. You might also not be aware of the fact that some of the most common functions that YUI provides are collected into one js file for easy usage. The comination of these two things is going to allow us to do many awesome things in the coming weeks.

Today's tip involves using the YUI DOM to access an element on the page and do something interesting with it.

Step 1: include the YUI library

To include the YUI library into your page, simply copy this line of code into the HEAD of your document: <script type="text/javascript" src="http://yui.yahooapis.com/2.2.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>

Step 2: determine element to access

Let's say you have an element on your page with an ID of "foopy" such as: <div id='foopy'>Hello World</div> Here is our div (with some styles to highlight it):

Hello World

Step 3: determine YUI code to access element

The YUI code you would use to access this element on the page would be: YAHOO.util.Dom.get('foopy'); Note that you don't have to use ID. You can pass into this get() function a DOM element reference such as document.body or you can pass in an array of element id's such as ['foopy','noopy','baz']. You can even pass in an array of DOM element references as well. The get() function will return an array of DOM elements which you can then do something interesting with!

Step 4: modify element to your liking

Once you have this element reference in javascript you can do anything you like with it. Let's change the background color when we click a link. Here's the link. And here's the js code: function changeEl(el){ var theEl = YAHOO.util.Dom.get(el); theEl.style.backgroundColor = 'red'; return false; }

I hope to have several of these very simple javascript tutorials. If you have ideas for YUI or general javascript tricks and tips, please email me and I'll consider it for a future Javascript Tip!

triptych at gmail dot com