JavaScript getElementsByClassName

Today I found myself writing a little bit of JavaScript to isolate an element on a page. The element in question looked something like this:

<div class="mulitcolumn">
    <p>Some text...</p>
    <p>Some more text</p>

I wanted to get the div element by searching for the class name multicolulmn. Without thinking, I began writing the code to grab the div using the getElementByClassName function. Then I remembered that getElementByClassName isn’t actually a built-in function. Oh well, Google to the rescue.

I was able to quickly find Robert Nyman’s elegant getElementsByClassName function in The Ultimate GetElementsByClassName.

Using this function, you can get elements like so (examples pulled from Nyman’s site):

// To get all a elements in the document with a “info-links” class.
getElementsByClassName(document, "a", "info-links");

// To get all div elements within the element named “container”, with a “col” and a “left” class.
getElementsByClassName(document.getElementById("container"), "div", ["col", "left"]);

I love it when I don’t have to write my own JavaScript.

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.