Inserting a new element before the end body tag using Yahoo Util DOM

Creating elements like divs, href links, paragraphs and more can be tricky. Suppose you do not have access to modify the html or you are dealing with a template file that is static to the entire application and need to add an element to the page on the fly. Using the YUI DOM utility you can do this simply by searching for an element by class name or id then appending the element to the page just where you want it. The code below gives you an example of how to use the getElementsByClassName method in YUI by searching for a body element with the class name of yui-skin-sam. Check out the YUI api for more helper methods.

//lets find the elements we need by finding all body elements that have the class yui-skin-sam
var elements = YAHOO.util.Dom.getElementsByClassName('yui-skin-sam', 'body');
//if you body does not have an ID then generate one usign the generateID method.
    var bodyid = YAHOO.util.Dom.generateId(elements[0],'body');
// Get the last child element of the body by searching for the body id we just created above.
    var bodyLastChild = YAHOO.util.Dom.getLastChild(bodyid);

// Now we create a DIV element using the standard javascript method createElement
		var b = document.createElement('div');
// Let YUI create and assign the new div elements id.
		var bottomid = YAHOO.util.Dom.generateId(b,'bottom');
    	b.href='#';
// Put some html in your div
		b.innerHTML = 'TESTER';
// Assign your div a class name of newClass so you can reference it in a style sheet.
		b.className = 'newClass';
// Attach the new DIV id to the element you are creating
		b.id = bottomid;
// Use YUI to insert the new div element afer the last child element of the body tag.
		YAHOO.util.Dom.insertAfter(b ,YAHOO.util.Dom.get(bodyLastChild));

Now to learn more on how to create ELEMENTS like divs and paragraphs check out the tutorials at W3cshools. This is sure to be a fun project to play and learn. Give it a try!

  • Technorati Favorites
  • DZone
  • Facebook
  • Slashdot
  • Yahoo Buzz
  • Twitter
  • Yahoo Bookmarks
  • Reddit
  • Digg
  • MySpace
  • StumbleUpon
  • LinkedIn
  • Delicious
  • Blogger Post
  • Bebo
  • Google Reader
  • Share/Bookmark

Comments are closed.