Get element by class name with JavaScript/jQuery
This post will discuss how to get elements by class name using JavaScript and jQuery.
1. Using jQuery – Class Selector
In jQuery, you can use the class selector ('.class') to select all elements with the given class.
$()
|
1 2 3 4 5 6 |
$(document).ready(function() { var objects = $(".main-class"); for (var obj of objects) { console.log(obj); } }); |
CSS
|
1 2 3 4 5 6 |
.main-class { width: 500px; height: 300px; border: 1px solid black; background-color: lightgray; } |
HTML
|
1 |
<div id="container" class="main-class"></div> |
Note that we can apply the same class to multiple elements within the document. So, it is advisable to fetch an element by its id.
2. Using JavaScript – getElementsByClassName() function
In pure JavaScript, you can use the native getElementsByClassName() method, which returns the NodeList of all elements having the given class.
JS
|
1 2 3 4 |
var objects = document.getElementsByClassName("main-class"); for (var obj of objects) { console.log(obj); } |
CSS
|
1 2 3 4 5 6 |
.main-class { width: 500px; height: 300px; border: 1px solid black; background-color: lightgray; } |
HTML
|
1 |
<div id="container" class="main-class"></div> |
3. Using JavaScript – querySelector() function
The querySelectorAll() method returns all elements within the document having the same class. To get the first element that matches the specified selector, you can use the querySelector() method.
JS
|
1 2 |
var object = document.querySelector(".main-class"); console.log(object); |
CSS
|
1 2 3 4 5 6 |
.main-class { width: 500px; height: 300px; border: 1px solid black; background-color: lightgray; } |
HTML
|
1 |
<div id="container" class="main-class"></div> |
That’s all about getting element by class name using JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)