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');
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With