getElementByClass JavaScript Function?

The getElementById is a very common JavaScript function that returns a reference to the element by its ID, but unfortunately when we try to use getElementByClass, the console returns the following error: Uncaught TypeError: document.getElementByClass is not a function.

In this article I’m going to present two workarounds to replace the getElementByClass JS function, with or without using jQuery.

getElementByClass javascript

Using jQuery

You can use the $(‘.testClass’) jQuery method to target elements by their class names if your project is using the jQuery library.
Here’s an example which you can test in this saved JSFiddle page. Use this HTML code:

<div class="testClass">
	A div with class="testClass".
</div>
<div class="testClass">
	The second div with the same class name.
</div>
<p class="testClass">
	A paragraph with testClass
</p>
<button type="button">Click to toggle</button>

And attach this script:

$("button").click(function(){
    $('.testClass').toggle();
});

Using Plain JavaScript

No worries if you don’t have jQuery included because we can use a function that is similar to the getElementsByClass: getElementsByClassName . This pure JS method returns an array of all elements in the document with the specified class name, as a NodeList object. Try it in this JSFiddle.

Here’s the code and how to use it:

<div class="testClass">
	A div with class="testClass".
</div>
<div class="testClass">
	The second div with the same class name.
</div>
<p class="testClass">
	A paragraph with testClass
</p>

<button onclick="testFunction();">Alert the content of the first testClass</button>

<script>
function testFunction() {
    var x = document.getElementsByClassName("testClass");
    alert(x[0].innerHTML);
}
</script>

This function is supported in all major browsers so you can go ahead and use it to target elements by their class names.