Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to get parent element by selector?

Tags:

javascript

dom

Example:

<div someAttr="parentDiv. We need to get it from child.">     <table>         ...         <td> <div id="myDiv"></div> </td>         ...     </table> </div> 

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'); 
like image 975
nkuhta Avatar asked Jan 09 '13 11:01

nkuhta


People also ask

How do you find the parent element?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it. In HTML, the document is itself the parent node of html element.

How do you find the parent element of a class?

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.

How do I select parent nodes?

Approach: Write a recursive function that takes the current node and its parent as the arguments (root node is passed with -1 as its parent). If the current node is equal to the required node then print its parent and return else call the function recursively for its children and the current node as the parent.


2 Answers

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.

like image 95
George Kargakis Avatar answered Oct 03 '22 23:10

George Kargakis


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); 
like image 21
Chris Avatar answered Oct 03 '22 23:10

Chris