Javascript DOM How to - Create custom method to get element by class name








Question

We would like to know how to create custom method to get element by class name.

Answer


<!DOCTYPE html>
<html>
<body>
  <a class="AAA">X</a>
  <a class="test">Test</a>
  <a class="BBB">X</a>
<script type='text/javascript'>
<!--from w w  w.j  a  v  a  2  s  .com-->
    HTMLElement.prototype.getElementsByClassName = function (classname) {
        return this.querySelectorAll('.' + classname);
    };
    document.body.getElementsByClassName('test')[0].style.color = 'red';

</script>
</body>
</html>

The code above is rendered as follows: