Get the parent of an element (JavaScript)
Getting the parent DOM element of an element in JavaScript:
Child
HTML code:
<div class="example">
<div class="child">Child</div>
</div>
JavaScript code:
<script>
// Getting the parent
var parent = document.querySelector('.child').parentElement;
// Printing the parent's tag name
document.querySelector('.child').textContent = parent.tagName;
</script>
Links
- Node: parentElement property developer.mozilla.org/en-US/docs/Web/API/Node/parentElement
Browser support
- Windows
- Edge 12.0+
- Firefox 9.0+
- Google Chrome 1.0+
- Opera 15.0+
- Linux
- Firefox 9.0+
- Google Chrome 1.0+
- Opera 15.0+
- iOS
- Safari 2.0+
- Android
- Samsung Internet 1.0+
- Chrome Android 18.0+
- Firefox for Android 9.0+
- Opera Android 14.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 a specified type (JavaScript)
- Select all given sibling elements between two other given sibling elements in JavaScript