hder
hder

Reputation: 77

JQuery - get first occurence of class travelling upwards anywhere in the DOM

I have several instances of class="reply_count", most embedded inside other elements. I would like a method to traverse upward anywhere in the DOM to get the first instance of, and get the text value.

In the example below, I tried using prevAll, and getting the first of them. However, it does not recognize the one that is within a DIV. That is the one I want to select. I assume prevAll works for the same level elements, but not nested ones?

My actual code is much more complex, but below is just a simple example of the intent.

What is another method of accessing the first occurrence of a class going upwards regardless of where it is and how it is nested in other elements?

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="reply_count">15</div>
        <div class="reply_count">10</div>
        <div><span class="reply_count">5</span></div>        
        <div id="click" style="cursor: pointer;">Click Here</div>
        <div class="reply_count">2</div>
        <div class="reply_count">1</div>
        <script>
            $("#click").click(function(){
                value = $(this).prevAll( ".reply_count:first" ).text();
                alert(value);
            });
        </script>  
</body>    
</html>

The result is: 10. I wanted 5.

Upvotes: 0

Views: 157

Answers (2)

Premshankar Tiwari
Premshankar Tiwari

Reputation: 3106

you can use closest method. It traverses upwards through the ancestors in the DOM tree and returns the closest parent matching your selector

Upvotes: 0

You can do something like this:

$(".click").click(function() {
  var c = $(this).parent().find(".reply_count").add(this);
  var t = $(c).index(this);
  var value = $(c).eq((t-1)).text();
  console.log(value);
});

Demo I've added multiple <div class="click" so you can see it working just fine.

$(".click").click(function() {
  var c = $(this).parent().find(".reply_count").add(this);
  var t = $(c).index(this);
  var value = $(c).eq((t-1)).text();
  console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="reply_count">15</div>
<div class="reply_count">10</div>
<div>4</div>
<div class="click" style="cursor: pointer;">Click Here</div>
<div><span class="reply_count">5</span></div>
<div class="click" style="cursor: pointer;">Click Here</div>
<div><span class="reply_count">1</span></div>

Upvotes: 1

Related Questions