JavaScript By Example

Document Object Model: 7. Get Parent Node

Man using a computer
Alistair Berg/Digital Vision/Getty Images

We are not limited to just getting the next and previous ndes at the same level within the document. The parentNode property provides us with direct access to the parent of the current node. This is actually far more useful than it first appears since many of the methods that we will use in order to update nodes will require that we first get the parent node.

In this example we'll get the parent of the node having a specific id and apply a background colour to that parent node.

In this instance the parent node is the body and so the entire page background will change colour. If you apply it to a node at a lower level then only part of your page would be affected.


<title>Example D07</title>
<div id="me">x</div>
<script type="text/javascript" src="exampleD07.js"></script>


var node;
node = document.getElementById('me').parentNode; = '#f00';