Javascript Get Element By ClassName
In this tutorial, we will learn how to select elements by their class name using JavaScript. A class name is a way of grouping elements that share some common styles or behaviors. We will see three examples of selecting elements by class name using different methods: querySelector, getElementsByClassName, and querySelectorAll.
written
reviewed
updated
Thanks for your feedback!
Your contributions will help us to improve service.
Js Get Element By Class | Single Class
Copied to Clipboard
2
// Select the first element with class "example"
const element = document.querySelector(".demoClass")
Javascript Find Element by Class | Multiple Class Access
Copied to Clipboard
6
<script>
const elements = document.getElementsByClassName('yourClassName');
for (var i = 0; i < elements.length; i++) {
elements[i].classList.add('highlighted');
}
</script>
Javascript querySelectorAll Example
Copied to Clipboard
7
<script>
const elements = document.querySelectorAll('.classname');
elements.forEach(element => {
element.style.border = '1px solid #999';
});
</script>
Ad