JavaScript By Example

Document Object Model: 7. Get Parent Node

Format
mla apa chicago
Your Citation
Chapman, Stephen. "JavaScript By Example." ThoughtCo, Nov. 24, 2014, thoughtco.com/javascript-by-example-get-parent-node-2037297. Chapman, Stephen. (2014, November 24). JavaScript By Example. Retrieved from https://www.thoughtco.com/javascript-by-example-get-parent-node-2037297 Chapman, Stephen. "JavaScript By Example." ThoughtCo. https://www.thoughtco.com/javascript-by-example-get-parent-node-2037297 (accessed October 21, 2017).
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.

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';

Format
mla apa chicago
Your Citation
Chapman, Stephen. "JavaScript By Example." ThoughtCo, Nov. 24, 2014, thoughtco.com/javascript-by-example-get-parent-node-2037297. Chapman, Stephen. (2014, November 24). JavaScript By Example. Retrieved from https://www.thoughtco.com/javascript-by-example-get-parent-node-2037297 Chapman, Stephen. "JavaScript By Example." ThoughtCo. https://www.thoughtco.com/javascript-by-example-get-parent-node-2037297 (accessed October 21, 2017).