Discovering Element Ancestry and Descendants with JavaScript DOM

In this tutorial, we will delve into the various methods for Discovering Element Parents, Children, and Siblings using JavaScript's DOM. The goal of this tutorial is to offer guidance, particularly to students and those new to JavaScript, on how to enhance their knowledge and skills in manipulating the Document Object Model (DOM) with JavaScript. I won't be using any additional JavaScript libraries like jQuery, and I'll provide code snippets to demonstrate the usage of JavaScript functions and methods for a more practical and thorough understanding.

Understanding JS DOM

JS DOM, or JavaScript Document Object Model, is a valuable programming interface for web documents. It serves as a representation of a web page's structure and provides developers with the ability to interact with and dynamically manipulate the content of a web page.

Why do we need to Find the Element Ancestors and Descendants?

While building a web application doesn't always require you to find elements' ancestors and descendants, this skill holds significant value in web development for several reasons:

  • Dynamic Content: Modern web applications often update their page content dynamically without the need for a full page reload. To achieve this functionality, the ability to locate element ancestors and descendants becomes crucial.
  • Event Handling: When handling events on specific elements, such as click, keypress, or hover actions, precise element targeting related to other elements is frequently necessary.
  • Data Extraction: There are situations where you may want to extract data from web pages, as is the case with web scraping. Accurate element identification plays a vital role in this process.
  • Styling: A solid understanding of the DOM structure is essential for applying CSS styles to specific elements or groups of elements.
  • DOM Manipulation: DOM manipulation often involves tasks like inserting, removing, or modifying elements. Precisely identifying the target elements is key to successful manipulation.
  • DOM Traversal: There are scenarios where you may need to navigate and manipulate the structure of a web page, including tasks like reordering or moving elements.

How to Find the Parent Element of a specific Element?

JavaScript provides two valuable properties known as parentNode and parentElement. These properties allow you to access and inspect the parent element of a particular element. Below is a code snippet that illustrates how to use these properties:


  1. <div class="container">
  2. <h2 id="page-title">Hello World!</h2>
  3. </div>


  1. // using parentNode property
  2. const elParentNode = document.getElementById('page-title').parentNode
  3. console.log(elParentNode)
  5. // using parentElement property
  6. const elParent = document.getElementById('page-title').parentElement
  7. console.log(elParent)


Finding the Element Parent in JS DOM

How to Find the Descendants Element of a specific Element?

To find the child or children elements of a DOM element, JavaScript provides several built-in functions, including getElementsByClassName(), querySelectorAll(), and querySelector().

The getElementsByClassName() method requires the class name of the child elements and returns an HTMLCollection that contains elements matching the provided class name.

The querySelectorAll() method requires an argument that identifies the child element we are targeting. The argument can be the element ID with a `#` character before it, a class name with a `.` before the name, an element tag name, or even an element hierarchy. This function returns a list of nodes that match the provided element.

The querySelector() method is similar to the querySelectorAll(). The main difference between these two functions is that querySelector() returns only the first matching node, whereas the other function returns all matching elements.

Here are the snippets the demonstrate the usage of these JS built-in functions:


  1. <div id="main">
  2. <h2 class="page-title">Hello World!</h2>
  3. <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ab repellat inventore quos praesentium! Non vel nostrum sit, ipsa quibusdam officiis autem at deleniti assumenda quia esse, sunt adipisci voluptatem architecto.</p>
  4. <ul>
  5. <li>Sample 101</li>
  6. <li>Sample 102</li>
  7. <li>Sample 103</li>
  8. <li>Sample 104</li>
  9. <li>Sample 105</li>
  10. </ul>
  11. </div>


  1. // Identify first the Parent Element
  2. const parentEl = document.getElementById('main')
  4. // The selecting the element child by classname
  5. const byClassName = parentEl.getElementsByClassName('page-title')
  7. // The selecting the element child using querySelector All
  8. const qrySelAll = parentEl.querySelectorAll('li')
  10. // The selecting the articular element child using querySelector
  11. const qrySel = parentEl.querySelector('p')
  13. console.log(byClassName)
  14. console.log(qrySelAll)
  15. console.log(qrySel)


Finding the Element Children in JS DOM

How to Find the Previous and Next Element of the Current Element?

To find an element's siblings, you can use the built-in JavaScript properties called nextElementSibling and previousElementSibling. The nextElementSibling property returns the next element that follows the selected element, while previousElementSibling returns the previous element. Take a look at the following sample snippet to get a better understanding of how to use these properties:


  1. <ul>
  2. <li class="first">Sample 101</li>
  3. <li class="second">Sample 102</li>
  4. <li class="third">Sample 103</li>
  5. <li class="fourth">Sample 104</li>
  6. <li class="fifth">Sample 105</li>
  7. </ul>


  1. // Getting the Next Elemetent
  2. const afterFirst = document.querySelector('li.first').nextElementSibling
  4. // Getting the Next Elemetent
  5. const beforeFift = document.querySelector('li.fifth').previousElementSibling
  7. console.log(afterFirst)
  8. console.log(beforeFift)


Finding the Element Siblings in JS DOM

JavaScript also offers a useful built-in method known as closest(). This method allows a selected element to traverse up the DOM hierarchy to the document root, searching for a node that matches the provided CSS selector. It returns null if no matching node is found, and if a match is found, it returns the matched element.

Here's a sample snippet that demonstrates the usage of this method:


  1. <div class="main-wrapper">
  2. <div class="wrapper first">
  3. <div class="wrapper second">
  4. <div class="third">
  5. <p class="content">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae ad reiciendis ex non? Culpa repellat aperiam, mollitia maiores deleniti rem nulla, repudiandae dicta similique, harum recusandae rerum eius ipsam nisi!</p>
  6. </div>
  7. </div>
  8. </div>
  9. </div>


  1. // Getting the Closest Element
  2. const el = document.querySelector('p.content').closest('.wrapper')
  4. console.log(el)


Finding the Closest Element in JS DOM


In conclusion, understanding the Element Ancestry and Descendants with JavaScript DOM allow us to build more dynamic web page and easily manipulates the page content or the DOM. Using the mentioned built-in properties, functions, and methods in JavaScript, we can target or select easily our target element parent, childrens, next/previous siblings, or nearest element.

That concludes our tutorial. I hope you'll discover great value in our guide on Exploring JavaScript DOM Element Ancestry and Descendants for enhancing your web application endeavors, both present and future.

Explore more on this website for more Free Source Codes, Tutorials, and Articles that covers various programming langugages.

Happy Coding =)

Add new comment