- 3 Ways JavaScript Add Class
- Add class javascript — 3 ways
- 1. Using classList property
- Adding class javascript on an event
- Add Multiple classes javascript
- 2. Using className property
- Adding multiple classes using className
- 3. Using setAttribute Method
- Adding multiple classes using setAttribute
- JavaScript add class to body
- JavaScript add class to div
- JavaScript add class to new element
- Add a class on hover javascript
- Conclusion
- Javascript add class on click
- # Add class to selected Elements on click
- # Additional Resources
- Add Class to Clicked Element Using JavaScript
- How to Add Class to Clicked Element Using JavaScript?
- Example 1: Add a Single Class to Clicked Element in JavaScript
- Example 2: Add Multiple Classes to Clicked Element in JavaScript
- Conclusion
- About the author
- Umar Hassan
3 Ways JavaScript Add Class
In this article, you will learn 3 different ways JavaScript add class to HTML elements. You will see different variations like adding multiple classes to the element, adding class to the body, creating a new element, etc.
You can either directly add a class to the element as an HTML attribute (Ex:
) or use JavaScript to add a class to the element (which we will see in this section).
Here is an example of adding a class to an HTML element using javascript.
// selecting the element let button = document.querySelector('#button'); // Add class to the element button.addEventListener('click', function() < button.classList.add('.main-btn'); >);
.main-btn < border: none; color: white; background: blue; padding: 10px 30px; border-radius: 5px; >@keyframes shake < 0% < transform: translateX(0) >25% < transform: translateX(-5px) >50% < transform: translateX(0) >75% < transform: translateX(5px) >100% < transform: translateX(0) >> .main-btn:hover
Output : Click the button below and javascript will add a class to the button.
This is a dynamic way of adding a class to an HTML element. Let’s see how javascript adds class dynamically to an HTML element.
Add class javascript — 3 ways
While working on the front end, we often need to add CSS dynamically to an HTML element. To add dynamic CSS to an element add a class to the element.
There are 3 ways to add CSS class using javascript.
1. Using classList property
Every HTML element has a classList property. This property has many different methods. One of the methods is add() method. This method is used to add a class to the element.
element.classList.add('class_name')
To add a CSS class using javascript follow the steps below:
- Select the HTML element.
- Apply the classList property to it.
- Use the add() method to add the class and pass the class name as an argument.
Adding class javascript on an event
In general, we add classes using javascript when an event occurs. For example, when a user clicks on a button, when a user scrolls down the page, etc.
Let’s see how to add a class to an HTML element when a user clicks on a button .
In the above code in the event of a button click a function is executed that adds a class to the paragraph element.
Add Multiple classes javascript
You can also add multiple classes at once using the add() method.
To add multiple classes at once, pass multiple classes separated by a comma.
2. Using className property
The className property of an element can be used to get and set classes attached to the element.
The className property returns the classes of the element in form of a string. If the element has a class named class1 then it returns «class1», if the element has 2 classes class1 and class2 then it returns «class1 class2», and so on.
const element1 = document.getElementById("id1"); const element2 = document.getElementById("id2"); console.log(element1.className); // "box" console.log(element2.className); // "big red box"
The className property can read as well as write the classes of the element.
To add a new class to the element assign the new class to the element’s className property as a string.
Note : Assigning a class name directly to the className property will overwrite the existing classes.
Here is an example to show this.
const element = document.getElementById("id1"); element.className = "box"; // all older classes will be replaced by box
To add new classes without replacing older classes use the += operator to assign the new class. It will keep older classes and adds new ones.
const element = document.getElementById("id1"); element.className += " box"; // must add space before class name // new class added, old one remained
Possible mistake : Add a space before the name of the class when using className to add a class. Because if the element has an old class «class1» and you add the new class «class2» it becomes «class1class2» which is meaningless to the browser.
Adding multiple classes using className
To add multiple classes assign new class names separated by spaces to the className property of the element.
3. Using setAttribute Method
setAttribute is a method that can be used to add a new attribute to an element.
A class is also an element attribute. So we can use the setAttribute method to add a class.
The setAttribute method can be used to add a new attribute to an element. The method takes two parameters, the name of the attribute and the value of the attribute.
// select the button var btn = document.getElementById('btn'); btn.addEventListener('click', function() < // add class btn.setAttribute('class', 'btn'); >);
Adding multiple classes using setAttribute
To add multiple classes to the element pass the multiple class names separated by spaces to the setAttribute method.
// select the button var btn = document.getElementById('btn'); btn.addEventListener('click', function() < // add class btn.setAttribute('class', 'btn danger'); >);
JavaScript add class to body
To add a class to the body of the webpage select the body by document.body and use either of the 2 mentioned methods to add CSS classes.
function addClass()
JavaScript add class to div
As mentioned above you can use any of the above 2 methods to add a class to a div element using javascript.
const div = document.getElementById("id1"); function addClass()
JavaScript add class to new element
Imagine a scenario where you want to add a new element to the webpage like creating a list item in a To Do list app. You can use the classList property to add a class to the new element.
To add multiple classes pass the class names separated by spaces to the classList.add() method.
Add a class on hover javascript
To add a class to an element when mouse hover use onmouseover event. Attach an onmouseover event to the element trigger event handler to add the class.
This is inside a div element const div = document.getElementById("id1"); function addClass()
Conclusion
Summarising the above methods to add a class to an element in JavaScript.
- Method 1 : Use classList.add() Method
- Method 2 : Use className property
- Method 3 : Use setAttribute() method
You can add single or multiple classes to an element using any of the above methods.
If you need assistance with your JavaScript project, feel free to contact experts for getting JavaScript assignment help online.
Javascript add class on click
You can pass as many classes to the add() method as necessary.
Copied!document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); >);
If any of the classes are already present on the element, they won’t get added a second time.
Similarly, if you need to remove one or more classes, you can use the remove() method.
Copied!document.addEventListener('click', function handleClick(event) event.target.classList.add( 'bg-yellow', 'second-class', 'third-class' ); event.target.classList.remove( 'second-class', 'third-class' ); >);
If any of the classes are not present on the element, they get ignored.
# Add class to selected Elements on click
To add a class to selected elements on click:
- Select a group of elements using the document.querySelectorAll() method.
- Use a for. of loop to iterate over the collection.
- On each iteration, add a click event listener to the element that adds a specific class.
Here is the HTML for this example.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> style> .bg-yellow background-color: yellow; > style> head> body> div class="box1">Box 1div> div class="box2">Box 2div> div class="box3">Box 3div> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const boxes = document.querySelectorAll('.box1, .box2, .box3'); for (const box of boxes) box.addEventListener('click', function handleClick() box.classList.add('bg-yellow'); >); >
We used the document.querySelectorAll method to select the DOM elements with classes box1 , box2 and box3 .
We used the for. of loop to iterate over the collection of elements and added a click event handler to each element.
We used the add() method to add a class to the clicked element.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Add Class to Clicked Element Using JavaScript
While creating a responsive web page or site, there can be a requirement to append various functionalities or effects upon user action or automatically. For instance, highlighting a specific section or element upon click/hover. In such situations, adding class to a clicked element using JavaScript is of great aid in engaging the users on a website and making it(site) stand out.
This write-up will discuss the approaches to add a class to a clicked element using JavaScript.
How to Add Class to Clicked Element Using JavaScript?
The “addEventListener()” method, in combination with the “classList” property and the “add()” method, can be applied to add a class to the clicked element using JavaScript.
The addEventListener() method associates an event with an element. The classList property gives the CSS class names of an element. Whereas the add() is a classList method used to add tokens to the list.
These approaches can be applied to attach an event and add a class to the element(s) based on that event.
- “event” refers to the specified event.
- “listen” is the function that needs to be invoked.
- “use” is the optional value.
Let’s elaborate on the concept with the help of the following examples!
Example 1: Add a Single Class to Clicked Element in JavaScript
In this example, a single class will be added to the clicked element(s):
document. addEventListener ( ‘click’ , function classClicked ( event ) {
event. target . classList . add ( ‘addedClass’ ) ;
background — color : greenyellow ;
In the above code snippet:
- Firstly, include the “ ” and “ ” elements, having the stated classes, respectively.
- Also, include a button in the next step.
- In the JS code block, apply the “addEventListener()” method to attach an event “click” to the function named “classClicked()”.
- Also, pass the object “event” as a function’s parameter.
- In the function definition, associate the “event” object with the “target” property. These approaches access the DOM elements upon the event trigger.
- Resultantly, the associated “classList” property and “add()” method will add the specified class to the element(s) upon click.
- In the CSS code, style the class to be appended, i.e., addedClass.
As observed in the above output, upon clicking the elements, the particular class is added to the elements.
Example 2: Add Multiple Classes to Clicked Element in JavaScript
In this particular example, multiple classes will be added to the clicked element(s):
document. addEventListener ( ‘click’ , function classClicked ( event ) {
event. target . classList . add ( ‘addedclass1’ , ‘addedclass2’ , ‘addedclass3’ ) ;
background — color : lightblue ;
Apply the following steps, as given in the above code:
- Include the stated “ ” elements having the specified classes.
- In the JavaScript code block, likewise, attach an event “click” to the function classClicked() using the “addEventListener()” method.
- Recall the discussed approaches to access elements on the DOM.
- Now, apply the “classList” property and “add()” method having multiple classes as its parameters.
- This will result in appending the stated multiple classes to the clicked element(s).
- In the CSS code, specify the classes that need to be added to the element(s) and perform the stated styling.
In this particular output, multiple classes are appended to each of the “>” elements upon the event trigger.
Conclusion
The “addEventListener()” method, in combination with the “classList” property and the “add()” method, can be applied to add a class to the clicked element using JavaScript. These approaches can be implemented to add single or multiple classes to element(s) based on the attached event. This write-up demonstrated to add a class to the clicked element using JavaScript.
About the author
Umar Hassan
I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.