Last updated: Mar 5, 2024
Reading time·2 min
To add a class to a parent element:
parentElement
property to get access to the parent node.classList.add()
method on the parent, passing it the class name as
a parameter.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> <style> .yellow-bg { background-color: yellow; } </style> </head> <body> <div data-id="parent-1"> <div id="child">Child 1</div> </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const child = document.getElementById('child'); child.parentElement.classList.add('yellow-bg');
We used the parentElement property on the node to get access to its parent.
The next step is to use the classList.add() method to add a class to the parent.
You can pass as many classes to the add()
method as necessary.
const child = document.getElementById('child'); child.parentElement.classList.add( 'yellow-bg', 'second-class', 'third-class' );
add()
method will omit the specific class.Similarly, if you need to remove one or more classes from the parent, use the
remove()
method.
child.parentElement.classList.add( 'yellow-bg', 'second-class', 'third-class' ); child.parentElement.classList.remove( 'yellow-bg', 'second-class' );
If you need to add a class to an element that isn't a direct parent of the node, use the closest() method to select the element.
closest()
method traverses the Element
and its parents until it finds a node that matches the provided selector.Let's say that we need to select the div
with id
of parent-1
in this
example.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> <style> .yellow-bg { background-color: yellow; } </style> </head> <body> <div id="parent-1" data-id="parent-1"> <span id="parent-2"> <div id="child">Child 1</div> </span> </div> <script src="index.js"></script> </body> </html>
Here is how we would add a class to the div
element using JavaScript.
const child = document.getElementById('child'); child.closest('#parent-1').classList.add('yellow-bg');
closest
method instead of the parentElement
property as we're trying to add a class to an element that isn't a direct parent.If the element itself matches the selector, the element is returned.
If no element that matches the provided selector exists, the closest()
method
returns null
.
The method takes a string that contains a selector. The provided selector can be as specific as necessary.
const child = document.getElementById('child'); child.closest('body > div#parent-1').classList.add('yellow-bg');
We used the closest()
method to select a div
element with an id
of
parent-1
, which has the body
element as its parent.
If an invalid selector string is provided to the closest()
method, a
SyntaxError
is thrown.
You can learn more about the related topics by checking out the following tutorials: