Find the closest ancestor element that has a specific class
Update: Now supported in most major browsers
document.querySelector("p").closest(".near.ancestor")
Note that this can match selectors, not just classes
https://developer.mozilla.org/en-US/docs/Web/API/Element.closest
For legacy browsers that do not support closest()
but have matches()
one can build selector-matching similar to @rvighne's class matching:
function findAncestor (el, sel) {
while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
return el;
}
Find closest ancestor of a clicked element from given array
See the comments inline below:
// Don't need Array.from() because the node list returned from
// .querySelectorAll() supports .forEach().
document.querySelectorAll('details.company-details').forEach(function(tab) {
tab.addEventListener('click', handleTabClick);
});
var elements = ['section', 'header', 'main', 'nav', 'article'];
let found = false;
let parent = null;
function handleTabClick(e) {
// Start at the parent of the tab
parent = this.parentNode;
// Keep looping until we find an ancestor that matches
while (found === false){
// Check the name of the parent element to see if its lower
// cased name is in the array.
if(elements.includes(parent.nodeName.toLowerCase())){
found = true; // Found a match
} else {
// No match. Get the next parent and keep looping
parent = getParent(parent);
}
}
console.log(parent);
};
function getParent(element){
return element.parentNode;
}
<main class="company-main-wrapper" id="maincontent">
<article>
<div class="company-grid-row">
<div class="company-grid-column-two-thirds">
<div class="company-page-content">
<div class="block-expander">
<details class="company-details company-expander" company-polyfilled="true" id="company-details0" open="">
<summary class="company-details__summary" role="button" aria-controls="company-details__text0" tabindex="0" aria-expanded="true">
<span class="company-details__summary-text">
sampoe page
</span>
</summary>
</details>
</div>
</div>
</div>
</div>
</article>
</main>
Find closest div that has a certain class
You can use CSS selector in .closest()
, just like that :
$(':checkbox').closest('div.required');
XPath get closest ancestor that has at least one p tag sibling
Assuming your xml looks like this:
<doc>
<div>
<div class="Not Looking for this div">
<span id="x"></span>
</div>
</div>
<div>
<p>...</p>
<div class="Looking for this div">
<span id="x"></span>
</div>
<p>...</p>
</div>
</doc>
This xpath expression
//span[@id="x"]/(ancestor::* [following-sibling::p | preceding-sibling::p])/@class
should output
Looking for this div
Jquery - Find the closest parent having a class name
To get the first one parent of specific class:
$(this).parents('.selectable').first();
jQuery closest div with specific class/id
To get the first ancestor, you can use closest()
method. As the closest()
method gives you the closest ancestor and the element you're looking for is not an ancestor, you can traverse to the closest parent element and then use find()
method to get the descendant element.
$('.produkttext img').on({
'mouseover': function(){
var images = $(this).attr('src');
$(this).closest('.grauereihe').find('img.bildtop').attr('src', images);
$(this).closest('.grauereihe').find('a.bildtopa').attr('href', images);
}
});
How to climb to specific parent element by JavaScript?
You can't move from child element to parent element using document.querySelector()
. However, there are multiple ways to select the parent of an element.
You can use Element.closest()
method to get the closest ancestor element with the specified CSS selector.
document.querySelector(".text").closest('.comments');
.closest()
method will traverse the .text
element and its ancestor elements (heading towards the document root) until it finds a node that matches the provided CSS selector.
If the element on which .closest()
method is called, matches the provided CSS selector, then that element is returned otherwise .closest()
method returns the matching ancestor or null
if not match is found.
Select the parent of the parent of an element
You can use Element.closest()
to find the first parent element that matches a selector, in our case, .parent1
:
const body = document.querySelector('body');
body.querySelector('button').addEventListener('click', function() {
this.closest('.parent1').classList.toggle('black');
});
.parent1 {
background: yellow;
padding: 20px;
}
.parent2 {
background: blue;
padding: 20px;
}
.black {
background: black;
}
<div class="parent1">
<div class="parent2">
<button>Click</button>
</div>
</div>
Related Topics
How to Get a File or Blob from an Object Url
How to Read the Post Request Parameters Using JavaScript
How to Save Canvas as an Image With Canvas.Todataurl()
Cross-Browser Multi-Line Text Overflow With Ellipsis Appended Within a Fixed Width and Height
Show Datalist Labels But Submit the Actual Value
Remember and Repopulate File Input
Referenceerror: Event Is Not Defined Error in Firefox
How to Change Div Content With JavaScript
How to Autosize a Textarea Using Prototype
How to Add Line Breaks to an HTML Textarea
How to Prevent Unicode Characters from Rendering as Emoji in HTML from JavaScript
Is There an Onselect Event or Equivalent For HTML ≪Select≫
How to Impose Maxlength on Textarea in HTML Using JavaScript
Difference Between Relative Path and Absolute Path in JavaScript
Difference Between Properties and Attributes in Html