JavaScript: Using relational properties to access elements



In JavaScript, it's sometimes useful to access the parent of an element or the element that comes next in the HTML file. In this section, we'll go over how to do that.

<div id="container">
    <p id="firstParagraph">
        <input type="button" id="button1" value="Button 1">

    <p id="secondParagraph">
        <input type="button" id="button2" value="Button 2">

How family relationships work in HTML

In the above example, #button1 is a child of #firstParagraph. You could also say #firstParagraph is the parent of #button1.

Similarly, #firstParagraph and #secondParagraph are siblings because they both have #container as their parent.

parentNode property


var button1 = document.querySelector('#button1');
var firstParagraph = button1.parentNode;

In this example, we were able to access #firstParagraph through the parentNode property of #button1.

nextElementSibling property


var firstParagraph = document.querySelector('#firstParagraph');
var secondParagraph = firstParagraph.nextElementSibling;

Similarly, since #secondParagraph is the next element after #firstParagraph, we were able to use the nextElementSibling property to access it.

previousElementSibling property

This property works exactly the same as nextElementSibling -- except it accesses the previous element in the HTML file.

Other relational properties

  • children
  • firstElementChild
  • lastElementChild

Leave a Comment