Previous and Next Element Siblings (DOM)

Previous and Next Element Siblings (DOM)

The Element.previousElementSibling and Element.nextElementSibling are read-only properties that returns the sibling element prior or following the specified element.

Use Case

One particular use case is a ratings component. The ratings component in the below example is composed of five span elements. Each span element has a css content property with the value containing '☆' and an active class where the content value changes to '⭐'.

When one of the span elements is clicked, the active class should be added to itself and all previous siblings relative to itself. Also, any active classes that may have been added to any next element siblings relative to itself should be removed.

The Psuedo code for the below is as follows:

Psuedo Code


import './styles.css';

document.getElementById("app").innerHTML = `
<div id='rating'>

let elem = document.querySelector('#rating')

//retrieve all spans inside #rating
let elems = document.querySelectorAll('#rating span')

//add a click event listener to each span
elems.forEach(elem => {
elem.addEventListener('click', function (event) {

      //add the active class to the clicked element

      //retrieve previous element sibling
      let prev = event.target.previousElementSibling

      //while the previous element sibling is not null
      while (prev) {
        //add the active class to the sibling

        //retrieve the value for the previous element sibling
        prev = prev.previousElementSibling;

      //retrieve next element sibling
      let next = event.target.nextElementSibling

      //while the next element sibling is not null
      while (next) {
        //add the active class to the sibling

        //retrieve the value for the next element sibling
        next = next.nextElementSibling;