Go to GoReading for breaking news, videos, and the latest top stories in world news, business, politics, health and pop culture.

JavaScript By Example: Get Parent Node

106 7


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.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D07</title>
</head>
<body>
<div>x</div>
<div>x</div>
<div id="me">x</div>
<div>x</div>
<div>x</div>
<div>x</div>
<script type="text/javascript" src="exampleD07.js"></script>
</body>
</html>

JavaScript


var node;
node = document.getElementById('me').parentNode;
node.style.background-color = '#f00';

Source...

Leave A Reply

Your email address will not be published.