Get Parent Element by Class

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.
Читайте также:  What is ldap authentication in java

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»)

Источник

Javascript get parent element with class

Last updated: Jan 11, 2023
Reading time · 5 min

banner

# Table of Contents

# Get the closest Parent element by Class using JavaScript

Use the closest() method to get the closest parent element by class, e.g. child.closest(‘.parent’) .

The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div class="parent"> div id="child">Child 1div> div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const child = document.getElementById('child'); const parentWithClass = child.closest('.parent'); console.log(parentWithClass); // 👉️ div.parent

get parent element by class

We got the child element by its id and called the closest() method on it.

The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

If the element itself matches the selector, the element is returned.

If no element matches the provided selector, the closest() method returns null .

The method takes a string that contains a selector. The provided selector can be as specific as necessary.

Copied!
const child = document.getElementById('child'); const parentWithClass = child.closest('div.parent'); console.log(parentWithClass); // 👉️ div.parent

The example matches only div elements that have the parent class.

The following example selects a div element that has a class of parent and has the body element as the parent.

Copied!
const child = document.getElementById('child'); const parentWithClass = child.closest('body > div.parent'); console.log(parentWithClass); // 👉️ div.parent

The following example returns the closest parent that has the parent class and is not a span element.

Copied!
const child = document.getElementById('child'); const parentWithClass = child.closest(':not(span).parent'); console.log(parentWithClass); // 👉️ div.parent

# Get the closest Parent element by Tag using JavaScript

You can also use the closest() method to get the closest parent element by tag.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div id="parent-1"> span id="parent-2"> div id="child">Child 1div> span> div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const child = document.getElementById('child'); // ✅ Gets immediate parent, regardless of which Tag const immediateParent = child.parentElement; console.log(immediateParent); // 👉️ span#parent-2 // ✅ Gets a parent that is a `div` element const parent = child.parentElement.closest('div'); console.log(parent); // 👉️ div#parent-1

We used the Node.parentElement property to get the DOM node’s immediate parent element.

However, the parentElement property doesn’t allow us to filter the results as it returns the parent element.

We used the closest method to get the closest parent element by tag.

The reason we accessed the parentElement property on the child before calling the closest() method is because the closest() method traverses the Element and its parents until it finds a node that matches the provided selector string.

In our case, the child is a div element and the parent we want access to is a div , so calling the closest() method and passing it a div selector returns the child element.

By accessing the parentElement property, we start traversing the DOM for an element that matches the selector from the parent element onwards.

If no element matches the selector, the closest() method returns null .

The method takes a string that contains a selector. The provided selector can be as specific as necessary.

Copied!
const child = document.getElementById('child'); // ✅ Gets a parent that is a `div` element const parent = child.parentElement.closest('body > div'); console.log(parent); // 👉️ div#parent-1

The example above selects a div element that has the body element as its parent.

If an invalid selector string is provided to the closest() method, a SyntaxError is thrown.

# Check if a Parent has a specific Class using JavaScript

To check if a parent element has a specific class:

  1. Pass the class selector as a parameter to the closest() method.
  2. If a parent with the specified class exists, the method returns the element.
  3. If no parent with the provided class exists, the method returns null .

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div class="parent-1"> div class="parent2"> div id="child">Box 1div> div> div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
// ✅ Check if any of the parent elements have class `parent-1` const child = document.getElementById('child'); const parentHasClass = child.closest('.parent-1') !== null; console.log(parentHasClass); // 👉️ true // ------------------------------------------------------------ // ✅ Check if the DIRECT parent element has class `parent-1`. const directParentHasClass = child.parentElement?.classList.contains('parent-1'); console.log(directParentHasClass); // 👉️ false

We used the Element.closest() method to select a parent element with the class of parent-1 .

The closest() method traverses the element and its parents until it finds a node that matches the provided selector.

If the element itself matches the selector, the element is returned.

If no element that matches the provided selector exists, the closest() method returns null .

The parentHasClass variable stores a boolean value:

  • true if there is a parent element of the div with id of child that contains the parent-1 class.
  • false if there isn’t.

This approach doesn’t specifically check if the direct parent element contains the class, it checks if a parent element anywhere in the hierarchy contains the provided class.

# Check if the direct parent of an element has a specific class

To check if the direct parent of the element has a specific class:

  1. Use the parentElement property to select the parent of the element.
  2. Use the classList.contains() method to check if the parent contains the class.
  3. The method returns true if the element’s class list contains the class and false otherwise.
Copied!
const child = document.getElementById('child'); // ✅ Check if the DIRECT parent element has class `parent-1`. const directParentHasClass = child.parentElement?.classList.contains('parent-1'); console.log(directParentHasClass); // 👉️ false

The parentElement property returns the DOM node’s parent element or null if the node has no parent or its parent is not a DOM element.

We used the optional chaining (?.) operator to short-circuit instead of throwing an error if the element has no parent.

The classList.contains method returns a boolean value — true if the class is contained in the element’s class list and false otherwise.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

JavaScript get parent element by class

To get the parent element of an element by its class name in JavaScript, you can use the querySelector method to select the element with the specified class, and then access its parent node using the parentNode property.

To get the parent element of an element by its class name in JavaScript, you can use the following syntax:

var element = document.querySelector('.your-class-name'); if (element) < var parentElement = element.parentNode; // You can now work with the parent element as needed console.log(parentElement); >else
var element = document.querySelector('.your-class-name'); if (element) < var parentElement = element.closest('.parent-class-name'); if (parentElement) < // You can now work with the parent element as needed console.log(parentElement); >else < console.log('Parent element not found.'); >> else

JavaScript gets parent element by class example

      

Hello, world!

var childElement = document.querySelector('.child-element'); if (childElement) < var parentElement = childElement.closest('.parent-element'); if (parentElement) < console.log(parentElement); // You can now work with the parent element as needed >else < console.log('Parent element not found.'); >> else

JavaScript get parent element by class

Comment if you have any doubts or suggestions on this Js element topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Источник

Оцените статью