Getting the parent div of element
The property pDoc.parentElement
or pDoc.parentNode
will get you the parent element.
You're looking for parentNode
, which Element
inherits from Node
:
parentDiv = pDoc.parentNode;
Handy References:
- DOM2 Core specification - well-supported by all major browsers
- DOM2 HTML specification - bindings between the DOM and HTML
- DOM3 Core specification - some updates, not all supported by all major browsers
- HTML5 specification - which now has the DOM/HTML bindings in it
If you are looking for a particular type of element that is further away than the immediate parent, you can use a function that goes up the DOM until it finds one, or doesn't:
// 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;
}
Edit 2021
Element.closest is part of the DOM standard. It takes a selector as an argument and returns the first matching ancestor or null if there isn't one.