In this article I’m going to present two workarounds to replace the getElementByClass JS function, with or without 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:
And attach this script:
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:
This function is supported in all major browsers so you can go ahead and use it to target elements by their class names.