- Instant help with your JavaScript coding problems

Add class to parent element in JavaScript

How to add class to parent element in JavaScript?

If you want to add a new CSS class to the current element's direct parent div, you can use the parentElement property. You can also use the parentNode property instead of the parentElement .

Once we have the parent element, we can easily add the desired CSS class in the usual way. Take the classList property and use the add method as shown in the example below.

    <div id="item-1">Item</div>
const element = document.getElementById('item-1');

if (element) {

As result, your DOM will change to:

<div class="new-class">
    <div id="item-1">Item</div>
Share "How to add class to parent element in JavaScript?"