Borislav Hadzhiev
Wed Dec 29 2021·2 min read
Photo by Toa Heftiba
To get an attribute of a parent node:
parentElement
property to get access to the parent node.getAttribute()
method on tha result, passing it the attribute name
as a parameter.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </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'); const attr = child.parentElement.getAttribute('data-id'); console.log(attr); // 👉️ "parent-1"
We used the parentElement property on the node to get access to its parent.
The next step is to use the Element.getAttribute() method, which returns the value of the specified attribute.
getAttribute()
method returns null
or ""
(empty string).If you need to get an attribute of an element that isn't a direct parent of the node, you can 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> <meta charset="UTF-8" /> </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 get an attribute of the div
element using JavaScript.
const child = document.getElementById('child'); const attr = child.closest('#parent-1').getAttribute('data-id'); console.log(attr); // 👉️ "parent-1"
We used the closest
method instead of the parentElement
property as we're
trying to access an attribute on 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'); const attr = child.closest('body > div#parent-1').getAttribute('data-id'); console.log(attr); // 👉️ "parent-1"
In the example above, we used the closest()
method to select a div
element
with an id
of parent-1
, which has the body
element as its parent.
closest()
method, a SyntaxError
is thrown.