Skip to content

JavaScript get parent element by class

  • by

To get the parent element of an element by its class name in JavaScript, you can use the querySelector method to select the element with the specified class, and then access its parent node using the parentNode property.

To get the parent element of an element by its class name in JavaScript, you can use the following syntax:

var element = document.querySelector('.your-class-name');
if (element) {
  var parentElement = element.parentNode;
  // You can now work with the parent element as needed
  console.log(parentElement);
} else {
  console.log('Element not found.');
}

Or

var element = document.querySelector('.your-class-name');
if (element) {
  var parentElement = element.closest('.parent-class-name');
  if (parentElement) {
    // You can now work with the parent element as needed
    console.log(parentElement);
  } else {
    console.log('Parent element not found.');
  }
} else {
  console.log('Element not found.');
}

JavaScript gets parent element by class example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Get Parent Element by Class</title>
</head>
<body>
  <div class="parent-element">
    <div class="child-element">
      <p>Hello, world!</p>
    </div>
  </div>

  <script>
    var childElement = document.querySelector('.child-element');
    if (childElement) {
      var parentElement = childElement.closest('.parent-element');
      if (parentElement) {
        console.log(parentElement); // You can now work with the parent element as needed
      } else {
        console.log('Parent element not found.');
      }
    } else {
      console.log('Child element not found.');
    }
  </script>
</body>
</html>

Output:

JavaScript get parent element by class

Comment if you have any doubts or suggestions on this Js element topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *