Skip to content

JavaScript find next element with class

  • by

To find the next element with a specific class using JavaScript, you can use the nextElementSibling property in conjunction with a loop. Here’s an example of how you can accomplish this:

function findNextElementWithClass(element, className) {
  // Get the next sibling of the given element
  var nextElement = element.nextElementSibling;

  // Loop through the siblings until we find an element with the desired class
  while (nextElement) {
    if (nextElement.classList.contains(className)) {
      return nextElement;
    }
    nextElement = nextElement.nextElementSibling;
  }

  // If no matching element is found, return null
  return null;
}

To use the function, you need to pass in the current element and the class name you are searching for. Here’s an example:

// Assuming you have an element with the id "currentElement"
var currentElement = document.getElementById("currentElement");
var nextElement = findNextElementWithClass(currentElement, "yourClassName");

if (nextElement) {
  // The next element with the specified class was found
  console.log(nextElement);
} else {
  // No matching element was found
  console.log("No matching element found.");
}

In the above code, replace "yourClassName" with the class name you want to find. The function will return the next element with that class, or null if no matching element is found.

JavaScript finds the next element with the class example

A simple example code finds the next element with a specific class in JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>Find Next Element with Class</title>
</head>
<body>
  <div class="element">Element 1</div>
  <div class="element">Element 2</div>
  <div class="element target">Target Element</div>
  <div class="element">Element 4</div>
  <div class="element">Element 5</div>

  <script>
    function findNextElementWithClass(element, className) {
      var nextElement = element.nextElementSibling;

      while (nextElement) {
        if (nextElement.classList.contains(className)) {
          return nextElement;
        }
        nextElement = nextElement.nextElementSibling;
      }

      return null;
    }

    var currentElement = document.querySelector('.target');
    var nextElement = findNextElementWithClass(currentElement, 'element');

    if (nextElement) {
      console.log(nextElement.textContent);
    } else {
      console.log('No matching element found.');
    }
  </script>
</body>
</html>

Output:

JavaScript find next element with class

If no matching element is found, it logs “No matching element found.”

Comment if you have any doubts or suggestions on this Js code topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading