KOMPX.COM or COMPMISCELLANEA.COM   

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

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