In this tutorial we will see How To Remove Class From All Elements using JavaScript. The querySelectorAll() method, remove() method and classList Property can be used to remove a class from all HTML elements.
Table of Contents
HTML querySelectorAll() Method
The querySelectorAll() Method returns all HTML elements which matches with the given CSS Selector.
In this example, it can also be used to get all elements with the same CSS Class.
HTML DOM classList Property
The HTML DOM classList Property returns the names of all Classes of HTML tag.
In this example classList Property is used to get all classes of all HTML tags. Then we can remove any particular class from all elements one by one.
HTML DOM remove() Method
The HTML DOM remove() Method removes the specific HTML element or node from the DOM.
In this example remove() Method is used to remove particular class from all HTML tags.
HTML Code
HTML Code is given below, In this code we have one button element, one paragraph element, one span tag and one h1 tag. All three elements have same class named 'text'.
<!DOCTYPE html>
<html>
<head>
<title>Remove Class From All Elements JavaScript</title>
<style>
.text { color: red;}
</style>
</head>
<body>
<span class="text">Span</span>
<p class="text">Paragraph</p>
<h1 class='text'>Heading</h1>
<button onclick="removeClass()">Click Me!</button>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, we have a function named removeClass(), which will be executed, once onclick event occurs for the button tag.
In the function, querySelectorAll() method is used to select all elements with class 'text', then inside for loop classList() method is used to get all classes of each element. Defined class is then removed using remove() method from all elements.
<script>
function removeClass()
{
var allElements = document.querySelectorAll(".text");
for(i=0; i<allElements.length; i++)
{
allElements[i].classList.remove('text');
}
}
</script>
Demo
Video Tutorial
Watch video tutorial on How To Remove Class From All Elements in JavaScript.