I ran into a problem where I wanted one single array of all of the pages list items’s where the only thing they had in common was that the parent parent node has a class name of  ”tabs”. Here is a slimed down version of what I had: 

<div main="main">
  <div class="tabs">
    <ul>
      <li>One</li>
    </ul>
  </div>
  <div class="tabs">
    <ul>
      <li>Two</li>
    </ul>
  </div>
</div>

One solution would be to find all of class=”tabs” then build an array, for each instance of tabs. Then combine them together. That is completely viable but YUI provides a better way, getElementsBy();

var listItems = YAHOO.util.Dom.getElementsBy( function() {
  return el.parentNode.parentNode.className == "tabs";
}, 'li', document.getElementById('main'));

It takes three params, 1) a function for each tested object to pass 2) an optional tag name to search for 3) a scope selector. Both 2 and 3 are optional.

Saves the day.

In my particular case, adding extra markup on the list item wasn’t possible, and YUI really saved me a ton of time. Nice work YUI.

One Response to “YAHOO.util.Dom.getElementsBy(); Saves the day!”

  1. Great article and very handy method. It might be worth making a small correction by adding el in the anonymous function declaration…. var listItems = YAHOO.util.Dom.getElementsBy( function(el /*<—*/) {
    return el.parentNode.parentNode.className == “tabs”;
    }, ‘li’, document.getElementById(‘main’));

    Andres

Leave a Reply