Deep in Javascript DOM Traversal 2

Fatemeh Paghar - Mar 1 - - Dev Community

Get the Children of an Element

In JavaScript, you can retrieve the child elements of a node using various properties and methods provided by the DOM (Document Object Model).

Here are some common ways to get child elements:

  • childNodes Property: Returns a NodeList containing all child nodes, including elements, text nodes, and comment nodes.
const parentElement = document.getElementById('parentId');
const childNodes = parentElement.childNodes;

// Filter only the element nodes
const childElements = Array.from(childNodes).filter(node => node.nodeType === 1);
Enter fullscreen mode Exit fullscreen mode
  • children Property: Returns an HTMLCollection containing only the child elements of the specified node.
const parentElement = document.getElementById('parentId');
const childElements = parentElement.children;
Enter fullscreen mode Exit fullscreen mode
  • firstChild and lastChild Properties: Retrieve the first and last child nodes, including text and comment nodes.
const parentElement = document.getElementById('parentId');
const firstChild = parentElement.firstChild;
const lastChild = parentElement.lastChild;
Enter fullscreen mode Exit fullscreen mode
  • firstElementChild and lastElementChild Properties: Access the first and last child elements, ignoring text and comment nodes.
const parentElement = document.getElementById('parentId');
const firstElement = parentElement.firstElementChild;
const lastElement = parentElement.lastElementChild;
Enter fullscreen mode Exit fullscreen mode
  • querySelectorAll Method: Use CSS selectors to query for specific child elements.
const parentElement = document.getElementById('parentId');
const childElements = parentElement.querySelectorAll('.childClassName');

Enter fullscreen mode Exit fullscreen mode

Get Siblings of an Element

Getting the siblings of an element refers to selecting other elements that share the same parent as the given element. In HTML, elements are arranged in a tree-like structure, and each element (except the root) has one parent element and can have multiple child elements.

In JavaScript, element.nextSibling and element.previousSibling are properties of DOM elements that allow you to access the next and previous sibling nodes, respectively, within the same parent node.

element.nextSibling:
The nextSibling property is a part of the Node interface in the DOM API. It helps you to get the next sibling node of the chosen element in the node tree. A sibling node is just another node that has the same parent node.

It's good to know that nextSibling includes all types of nodes, like elements, texts, or comments. This could cause surprises if your HTML has spaces or comments in its structure.

element.previousSibling:

The previousSibling property helps to retrieve the node just before the given node as a Node object. If the given node is the first one in the list, the property returns null.

It points to the element that comes before the specified one on the same level of the tree. It returns the preceding sibling node, which could be a text node, element node, or comment node. This property is read-only for the web page.

Keep in mind that the children's property retrieves all children of an element. We can use previousSibling to access the previous sibling node in functions like alert, console, and innerHTML.

Here's an example demonstrating the use of these properties:

<ul>
  <li id="first">First</li>
  <li>Second</li>
  <li id="target">Third</li>
  <li>Fourth</li>
  <li id="last">Fifth</li>
 </ul>
Enter fullscreen mode Exit fullscreen mode
<script>
  var targetElement = document.getElementById("target");

  // Accessing next sibling
  var nextSibling = targetElement.nextSibling;
  console.log("Next Sibling:", nextSibling);

  // Accessing previous sibling
  var previousSibling = targetElement.previousSibling;
  console.log("Previous Sibling:", previousSibling);
</script>
Enter fullscreen mode Exit fullscreen mode

In this example, assuming targetElement refers to the <li> element with the id "target", nextSibling will be the <li> element with the text "Fourth", and previousSibling will be the <li> element with the text "Second".

Node.nextElementSibling and Node.previousElementSibling:

The Node.nextElementSibling and Node.previousElementSibling properties function similarly to Node.nextSibling and Node.previousSibling, but they specifically retrieve the next and previous sibling elements of the target element, excluding text nodes and comment nodes.

For instance, if we consider the example markup again, using nextElementSibling would fetch the list item (li) with "Neville" instead of a comment node.

<ul>    
 <li>Item 1</li>
 <li>Item 2</li>
 <li id="item3">Item 3</li> 
 <li>Item 4</li>
</ul>

let item = document.querySelector('#item3');

// returns <li>item 4</li>
let next = item.nextElementSibling;

// returns <li>item 2</li>
let previous = item.previousElementSibling;

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .