OVERTONE OVERTONE - 3 months ago 8
CSS Question

Getting parent div of element (javascript)

This should be really simple but I'm having trouble with it. How do I get a parent div from a child element.

e.g

HTML



<div id="test>
<p id="myParagraph">Testing</p>
</div>


Javascript



var pDoc = document.getElementById("myParagraph");
var parentDiv = ??????????


I would have thought
document.parent
or
parent.container
would work but I keep getting
not defined
errors. Note that the
pDoc
is defined, just not certain variables of it.

Any ideas?

P.S. I would prefer to avoid JQuery if possible.

Answer

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
Comments