Get the parent of a specified type (JavaScript)
Getting an ancestor DOM element by a specified attribute (class, id, etc) or tag in JavaScript. Going up toward the document root from an element until finding an ancestor matching the specified selector:
Child
HTML code:
<div class="example">
<div class="child">Child</div>
</div>
JavaScript code:
<script>
// Getting an ancestor specified by a class
var parent = document.querySelector('.child').closest('.main');
// Printing the ancestor's class name
document.querySelector('.child').textContent = parent.tagName;
</script>
Links
- Element: closest() method developer.mozilla.org/en-US/docs/Web/API/Element/closest
Browser support
- Windows
- Edge 15.0+
- Firefox 35.0+
- Google Chrome 41.0+
- Opera 28.0+
- Linux
- Firefox 35.0+
- Google Chrome 41.0+
- Opera 28.0+
- iOS
- Safari 9.0+
- Android
- Samsung Internet 4.0+
- Chrome 41.0+
- Firefox 35.0+
- Opera 28.0+
More
- Accessing the first element in forEach loop (JavaScript)
- Click event only on parent, not children
- Detecting a newly generated element and adding a class to it in JavaScript
- Get the parent of an element (JavaScript)
- Select all given sibling elements between two other given sibling elements in JavaScript