Wednesday, May 16, 2007

YUI's getElementsByClassname

YUI has a lot of useful shortcut and helper functions. One that has been helpful to me recently is YAHOO.util.Dom.getElementsByClassName.

It returns a javascript array of html elements that have the same classname. This is particularly useful if you want to change the look of a group of html elements like say in a menu bar or in a navigation sidebar.

The snippet below uses getElementsByClassName to get all html elements with a class "sidebarbtn". It also allows you to further qualify what type of html element. In the example below, we are looking for "div" elements with the class "sidebarbtn".

var els = YAHOO.util.Dom.getElementsByClassName('sidebarbtn', 'div');

for (var i =0; i <= els.length; i++) {
YAHOO.util.Dom.removeClass(els[i], "selectedbtn");

}

YAHOO.util.Dom.addClass(selected,"selectedbtn");

2 comments:

  1. Thanks for this article, it gave me direction.

    ReplyDelete
  2. there is a third argument that you can pass the container element to further speed up this function

    ReplyDelete