CodePug.com

Home | Games | Media | Programming | Raspberry Pi | Misc Content

Find a DOM Element by Its Class Name

When using JavaScript UI frameworks such as jQuery, it is relatively trivial to select an object on the page (in the DOM) by its class name. For example to retrieve the contents of <div class="pug"></div>, one would simply use code similar to the following.

However, for those instances when a lighter framework-free approach is desired, the same result can be achieved just by adding the two methods in the code snippet below. This method can be tested by which will output the value of the button.

JavaScript Code Snippet

/*

document.getElementByClass = function(classToFind){ return document.getElementsByClassName(classToFind)[0]; } </code>