Add class to parent element in JavaScript
Question:
How to add class to parent element in JavaScript? Answer:
element.parentElement.classList.add('new-class');
Description:
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>
<div id="item-1">Item</div>
</div>
const element = document.getElementById('item-1');
if (element) {
element.parentElement.classList.add('new-class');
}
As result, your DOM will change to:
<div class="new-class">
<div id="item-1">Item</div>
</div>
Reference:
parentElement reference
Share "How to add class to parent element in JavaScript?"
Related snippets:
- Create HTML element with attributes in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get elements by data attribute in JavaScript
- Add class to the clicked element in JavaScript
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add data attribute to element in JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Toggle fullscreen and normal mode with JavaScript
- Play video in fullscreen with vanilla JavaScript
- Select HTML elements by CSS selectors in vanilla JavaScript
- Exit from fullscreen mode on click in JavaScript
- Switch browser to fullscreen mode with JavaScript
- Get the value of text input field in JavaScript
- Get element with data- attribute using vanilla JavaScript
- Get the value of selected radio button in JavaScript
- Get selected option from select using JavaScript
- Check if element is hidden in JavaScript
Tags:
add, class, parent, element, div, vanilla, javascript Technical term:
Add class to parent element in JavaScript