Problem
This should be easy, but I’m having difficulty with it. How do I retrieve a child element’s parent div?
My HTML:
<div id="test">
<p id="myParagraph">Testing</p>
</div>
My JavaScript:
var pDoc = document.getElementById("myParagraph");
var parentDiv = ??????????
I figured document.parent or parent.container would do the trick, but I keep getting not defined problems. It’s worth noting that the pDoc is defined, but only some of its variables are.
Any ideas?
P.S. If at all possible, I’d like to avoid using jQuery.
Asked by OVERTONE
Solution #1
You’re seeking for parentNode, a property of Node that Element inherits:
parentDiv = pDoc.parentNode;
Handy References:
Answered by T.J. Crowder
Solution #2
You can use a function that climbs up the DOM until it discovers, or doesn’t find, a specific sort of element that is further away than the immediate parent:
// Find first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
The DOM standard includes Element.closest. It takes a selector as an argument and returns the first ancestor that matches it, or null if none exists.
Answered by RobG
Solution #3
The parent element can be retrieved using the pDoc.parentElement or pDoc.parentNode properties.
Answered by Thor Jacobsen
Solution #4
parentDiv = pDoc.parentElement; var parentDiv = pDoc.parentElement; var parentDiv = p
In some circumstances, this is also known as parentNode.
Answered by LoganDark
Solution #5
This could be beneficial to you.
ParentID = pDoc.offsetParent;
alert(ParentID.id);
Answered by Sinan ÇALIŞKAN
Post is based on https://stackoverflow.com/questions/6856871/getting-the-parent-div-of-element