Find the previous element with specific class using JavaScript

Find the Previous Element with specific Class using JS

You will know how to find the previous element with specific class using JavaScript with two methods: using a loop with a property and using prev() from jQuery. This is one of the most important skills when you work with DOM elements in Javascript.

How to find the previous element with specific class using JavaScript?

Using a for loop and previousElementSibling property

This previousElementSibling property will return the previous element in the same level. You can use a for loop and each iterator is the previous element of the current element that the iterator is looping through:

<html>
    <body>
    <h1 class="study">LEARN SHARE IT</h1>
    <h1 class="relax" id = "result">LEARN SHARE IT 2</h1>
    <h1 class="play">LEARN SHARE IT 3</h1>
    <h1 id="begin">LEARN SHARE IT 4</h1>
    <script>
        // Get elements with the id 'begin'.
        let begin = document.getElementById("begin");
        
        // Find the previous element with the specific class 'relax'
        for (i = begin.previousElementSibling; i; i = i.previousElementSibling)
            if (i.classList.contains("relax"))
                break

        // Get the result
        document.getElementById("result").innerHTML = i.className + i 
        console.log(i)
    </script>
  </body>
</html>

Output

<h1 class="relax" id="result">relax[object HTMLHeadingElement]</h1>

In the above example, we use a for loop with each iterator as the previous element sibling of the current element. The loop will stop if the condition of the presence of the specific class is met or there is no more iterator (i is null) to loop through. In this case, the class name is “relax”. As a result, we get the h1 tag which is of this class like the output above.

Using prev()

This method will return immediately the preceding sibling of an element that matches with a CSS selector given.

Syntax:

prev(selector)

Parameter:

  • selector: a valid CSS selector string to find the class name.

To use this method, you must import the jQuery library in your script tag and learn how to write CSS selectors in order that you can choose a specific class.

<html>
    <body>
    <h1 class="relax" id = "result">LEARN SHARE IT</h1>
    <h1 class="study">LEARN SHARE IT 2</h1>
    <h1 class="relax">LEARN SHARE IT 3</h1>
    <h1 id="begin">LEARN SHARE IT 4</h1>
    <script src  ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
    <script>
        // Get the element with the id 'begin'.
        let begin = $("h1");
        
        // Find the previous element with the specific class 'relax'
        let result = begin.prev(".relax")

        // Get the result
        result.html("Found relax")
        console.log(result)
    </script>
  </body>
</html>

Output: 

jQuery.fn.init(2) [h1#result.relax, h1.relax, prevObject: jQuery.fn.init(4)]
Found relax
LEARN SHARE IT 2
Found relax
LEARN SHARE IT 4

The login behind this method is very simple, as we want to find the previous h1 element with specific class “relax”, we use the css “.relax” to indicate the class name we are looking for. As you can see, if you use this approach, it will make change to all the h1 element whose previous element is of class “relax” instead of one element with id “begin” as in the first solution.

Summary

We have learned how to find the previous element with specific class using JavaScript with two different approaches. We suggest you use the first approach as it is a built-in method. You can read more about working with elements’ class names in the article: How To Hide An Element By Class Using JavaScript?

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *