JavaScript getElementsByClassName

Today I found myself writ­ing a little bit of JavaScript to iso­late an ele­ment on a page. The ele­ment in ques­tion looked some­thing like this:

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

I wanted to get the div ele­ment by search­ing for the class name multicolulmn. With­out think­ing, I began writ­ing the code to grab the div using the getElementByClassName func­tion. Then I remem­bered that getElementByClassName isn’t actu­ally a built-​in func­tion. Oh well, Google to the rescue.

I was able to quickly find Robert Nyman’s ele­gant getElementsByClassName func­tion in The Ulti­mate GetEle­ments­By­Class­Name.

Using this func­tion, you can get ele­ments like so (exam­ples 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. You can leave a response, or trackback from your own site.

Leave a Reply