Get Attribute of a Parent Node using JavaScript

avatar

Borislav Hadzhiev

Wed Dec 29 20212 min read

banner

Photo by Toa Heftiba

Get Attribute of a Parent Node using JavaScript #

To get an attribute of a parent node:

  1. Select the child element.
  2. Use the parentElement property to get access to the parent node.
  3. Call the getAttribute() method on tha result, passing it the attribute name as a parameter.

Here is the HTML for the examples in this article.

index.html
<!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.

index.js
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.

If the provided attribute does not exist on the element, the 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.

The 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.

index.html
<!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.

index.js
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.

index.js
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.

If an invalid selector string is provided to the closest() method, a SyntaxError is thrown.
Use the search field on my Home Page to filter through my more than 1,000 articles.