- Element: closest() method
- Syntax
- Parameters
- Return value
- Exceptions
- Examples
- HTML
- JavaScript
- Specifications
- Browser compatibility
- Compatibility notes
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- 5 Techniques to Get Parent Element with Class in JavaScript and jQuery
- Using the closest() method
- Using the parentNode property
- Using jQuery’s parent() and parents() methods
- Using the querySelector() method
- Using the closest() method with a for loop
- Other helpful code examples for getting the parent element with class in JavaScript
- Conclusion
- Frequently Asked Questions — FAQs
- How can I get the parent element with a class using vanilla JavaScript?
- What is the difference between `parent()` and `parents()` methods in jQuery?
- Which technique is more efficient to get the parent element with a class in JavaScript?
- Can I use the `querySelector()` method to get the parent element with a class in JavaScript?
- Is it possible to use a for loop to find the parent element with a class in JavaScript?
- How do I decide which technique to use to get the parent element with a class in JavaScript?
- JavaScript: How to get parent element by selector?
- 11 Answers 11
- Usage example
- Using leech’s answer with indexOf (to support IE)
- To select by class name:
- To select by ID:
Element: closest() method
The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
Syntax
Parameters
A string of valid CSS selector to match the Element and its ancestors against.
Return value
The closest ancestor Element or itself, which matches the selectors . If there are no such element, null .
Exceptions
Thrown if the selectors is not a valid CSS selector.
Examples
HTML
article> div id="div-01"> Here is div-01 div id="div-02"> Here is div-02 div id="div-03">Here is div-03div> div> div> article>
JavaScript
const el = document.getElementById("div-03"); // the closest ancestor with the id of "div-02" console.log(el.closest("#div-02")); // // the closest ancestor which is a div in a div console.log(el.closest("div div")); // // the closest ancestor which is a div and has a parent article console.log(el.closest("article > div")); // // the closest ancestor which is not a div console.log(el.closest(":not(div)")); //
Specifications
Browser compatibility
BCD tables only load in the browser
Compatibility notes
- In Edge 15-18 document.createElement(tagName).closest(tagName) will return null if the element is not first connected (directly or indirectly) to the context object, for example the Document object in the case of the normal DOM.
See also
Found a content problem with this page?
This page was last modified on Jul 22, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
5 Techniques to Get Parent Element with Class in JavaScript and jQuery
Learn how to easily get the parent element with a specific class using vanilla JavaScript and jQuery. Try these efficient techniques and improve your web development skills now!
- Using the closest() method
- Using the parentNode property
- Using jQuery’s parent() and parents() methods
- Using the querySelector() method
- Using the closest() method with a for loop
- Other helpful code examples for getting the parent element with class in JavaScript
- Conclusion
- How to get the parent of an element in JavaScript?
- How do I find my parent class?
- How to get closest class in JavaScript?
- How to get the grandparent element in JavaScript?
JavaScript is a powerful language that allows developers to manipulate the DOM and interact with web pages in a variety of ways. One common task is to get the parent element of an HTML element with a specific class. In this post, we’ll explore several techniques for achieving this using vanilla JavaScript and jQuery.
Using the closest() method
The closest() method of the Element interface allows you to traverse up the DOM tree and find the closest parent element with a specified selector. To get the parent element with a specific class, simply pass the class selector as a parameter to the closest() method. It’s important to note that the closest() method includes the starting element, so you’ll need to start searching from the parent element to find the closest one with the desired class.
Here’s an example of using the closest() method to get the parent element with a specific class:
element.closest('.parent-class')
Using the parentNode property
Another way to get the parent element of an HTML element with a specific class is to use the parentNode property. This property returns the parent element of the specified element, so you can loop through the parent elements until you find one with the desired class. However, this method can be less efficient than using the closest() method, especially when dealing with deeply nested elements.
Here’s an example of using the parentNode property to get the parent element with a specific class:
Using jQuery’s parent() and parents() methods
jQuery offers two methods for getting the parent element(s) of a selected element: parent() and parents() . The parent() method returns the immediate parent element of the selected element, while the parents() method returns all parent elements up to the document root. To get the parent element with a specific class, you can chain the parent() or parents() method with the hasClass() method to test for the presence of the desired class.
Here’s an example of using jQuery’s parent() method to get the parent element with a specific class:
Or, you can use jQuery’s parents() method to get all parent elements with a specific class:
$(element).parents('.parent-class').eq(0)
Using the querySelector() method
The querySelector() method allows you to select the first element in the document that matches a specified CSS selector. To get the parent element with a specific class, you can use the querySelector() method to get the child element with the desired class, and then use the parentNode property to get its parent element.
Here’s an example of using the querySelector() method to get the parent element with a specific class:
element.querySelector('.parent-class').parentNode
Using the closest() method with a for loop
In cases where the closest() method isn’t sufficient, you can use a for loop to climb up the DOM tree and find the closest parent element with a matching selector. This method involves starting at the selected element’s parent element and repeatedly calling the parentNode property until a matching element is found.
Here’s an example of using a for loop to get the parent element with a specific class:
let parent = element.parentNode; while (parent) < if (parent.classList.contains('parent-class')) < return parent; >parent = parent.parentNode; >
Other helpful code examples for getting the parent element with class in JavaScript
In Javascript , in particular, javascript find parent with class
document.querySelector("p").closest(".near.ancestor")
In Javascript , for example, javascript node has parent with class
/** * If the element/node ('child') has the class 'classname' => return true * Else: call the function again with parent until parent with class is found or no parent is left */ function hasParentClass(child, classname)< if(child.className.split(' ').indexOf(classname) >= 0) return true; try< //Throws TypeError if child doesn't have parent any more return child.parentNode && hasParentClass(child.parentNode, classname); >catch(TypeError) < return false; >>
Object.getPrototypeOf(instance.constructor).name // == "Parent"
Conclusion
Getting the parent element with a specific class using JavaScript is a common task that can be accomplished in several ways. The closest() method, parentNode property, jQuery’s parent() and parents() methods, querySelector() method, and a for loop can all be used to achieve this. When deciding which method to use, consider the efficiency of each approach and the complexity of your use case.
Frequently Asked Questions — FAQs
How can I get the parent element with a class using vanilla JavaScript?
You can use the `closest()` method or the `parentNode` property to achieve this. The `closest()` method allows you to traverse up the DOM tree and find the closest parent element with a specified selector, while the `parentNode` property returns the parent element of the specified element.
What is the difference between `parent()` and `parents()` methods in jQuery?
The `parent()` method returns the immediate parent element of the selected element, while the `parents()` method returns all parent elements up to the document root.
Which technique is more efficient to get the parent element with a class in JavaScript?
The `closest()` method is generally considered the most efficient technique for getting the parent element with a class in JavaScript.
Can I use the `querySelector()` method to get the parent element with a class in JavaScript?
Yes, you can use the `querySelector()` method to select the first element in the document that matches a specified CSS selector and then use the `parentNode` property to get its parent element.
Is it possible to use a for loop to find the parent element with a class in JavaScript?
Yes, you can use a for loop to climb up the DOM tree and find the closest parent element with a matching selector. However, this method may be less efficient than other techniques.
How do I decide which technique to use to get the parent element with a class in JavaScript?
When deciding which technique to use, consider the efficiency of each approach and the complexity of your use case. For example, the `closest()` method is generally considered the most efficient, but may not be suitable for deeply nested elements.
JavaScript: How to get parent element by selector?
I want to get the parent by some selector from the inner div element (the one with the myDiv class). How do I achieve that with plain JavaScript, without jQuery? Something like:
var div = document.getElementById('myDiv'); div.someParentFindMethod('some selector');
Note that this question is looking for ancestor elements matching a query; for anyone looking for only the parent element, try element.parentNode or if it needs to match a query, something like element.parentNode.matches(‘.some-query’) ? element.parentNode : null
11 Answers 11
You may use closest() in modern browsers:
var div = document.querySelector('div#myDiv'); div.closest('div[someAtrr]');
Use object detection to supply a polyfill or alternative method for backwards compatability with IE.
Considering we are in 2018 and Edge supports this method, I think this answer should be the accepted one. 🙂
Here’s the most basic version:
function collectionHas(a, b) < //helper function (see below) for(var i = 0, len = a.length; i < len; i ++) < if(a[i] == b) return true; >return false; > function findParentBySelector(elm, selector) < var all = document.querySelectorAll(selector); var cur = elm.parentNode; while(cur && !collectionHas(all, cur)) < //keep going up until you find a match cur = cur.parentNode; //go up >return cur; //will return null if not found > var yourElm = document.getElementById("yourElm"); //div in your original code var selector = ".yes"; var parent = findParentBySelector(yourElm, selector);
This is rather inefficient in that it retrieves all elements with that selector in the entire document, rather than just checking the parent.
This JSPerf test analyzes Element.matches() , Element.closest() , and one polyfill for each of those methods. The polyfill for Element.matches() looks very similar to your implementation. To address the performance concern of @user663031, perhaps you could use Element.matches() instead of Document.querySelectorAll() . It appears to run faster than the related polyfill.
Finds the closest parent (or the element itself) that matches the given selector. Also included is a selector to stop searching, in case you know a common ancestor that you should stop searching at.
function closest(el, selector, stopSelector) < var retval = null; while (el) < if (el.matches(selector)) < retval = el; break >else if (stopSelector && el.matches(stopSelector)) < break >el = el.parentElement; > return retval; >
closest is a shitty name, should be named «closestAncestor» , if the closest ancestor is 10 elements up and the closest descendant is 1 child down, the «closest» will be the descendant, not the ancestor, but this function will return the ancestor instead
By using querySelector() and closest() methods is possible to get the parent element.
- querySelector() returns the first element that matches a specified CSS selector(s) in the document.
- closest() searches up the DOM tree for the closest element which matches a specified CSS selector.
Usage example
const element = document.querySelector('td') console.log(element.closest('div'))
In case of needing to select more than one element, querySelectorAll() is a good fit.
- querySelectorAll() returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.
To select the desired element, is necessary to specify it inside [] so, for example for the second element would be: element[1]
const el = document.querySelectorAll('td') console.log(el[1].closest('tr'))
Using leech’s answer with indexOf (to support IE)
This is using what leech talked about, but making it work for IE (IE doesn’t support matches):
function closest(el, selector, stopSelector) < var retval = null; while (el) < if (el.className.indexOf(selector) >-1) < retval = el; break >else if (stopSelector && el.className.indexOf(stopSelector) > -1) < break >el = el.parentElement; > return retval; >
It’s not perfect, but it works if the selector is unique enough so it won’t accidentally match the incorrect element.
Here’s a recursive solution:
function closest(el, selector, stopSelector)
I thought I would provide a much more robust example, also in typescript, but it would be easy to convert to pure javascript. This function will query parents using either the ID like so «#my-element» or the class «.my-class» and unlike some of these answers will handle multiple classes. I found I named some similarly and so the examples above were finding the wrong things.
function queryParentElement(el:HTMLElement | null, selector:string) < let isIDSelector = selector.indexOf("#") === 0 if (selector.indexOf('.') === 0 || selector.indexOf('#') === 0) < selector = selector.slice(1) >while (el) < if (isIDSelector) < if (el.id === selector) < return el >> else if (el.classList.contains(selector)) < return el; >el = el.parentElement; > return null; >
To select by class name:
let elementByClassName = queryParentElement(someElement,».my-class»)
To select by ID:
let elementByID = queryParentElement(someElement,»#my-element»)