Using a for loop and previousElementSibling property
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>
<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.
This method will return immediately the preceding sibling of an element that matches with a CSS selector given.
- 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>
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.
Maybe you are interested:
- Check if an Element does NOT have specific Class using JS
- Update all dom elements with a specific class using js
Name of the university: HCMUT