Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element not directly in dom path

Tags:

jquery

dom

I have a dom structure that looks something like (although a lot more complex)

<div>
  <div>
    <div>
      <div class="remaining">132</div>
    </div>
  </div>
  <div>
    <button>clicky</button>
  </div>
</div>
<div>
  <div>
    <div>
      <div class="remaining">142</div>
    </div>
  </div>
  <div>
    <button>clicky</button>
  </div>
</div>
<div>
  <div>
    <div>
      <div class="remaining">152</div>
    </div>
  </div>
  <div>
    <button>clicky</button>
  </div>
</div>

As you can see the divs with class remaining arn't directly in the dom path of the relative buttons.

How can I when the button is clicked, increment the relative remaining div by 1?

like image 492
Hailwood Avatar asked Dec 09 '25 02:12

Hailwood


1 Answers

Give the common parent some meaningful class:

<div class="meaningful">
  <div>
    <div>
      <div class="remaining">152</div>
    </div>
  </div>
  <div>
    <button>clicky</button>
  </div>
</div>

Then you can use .closest() and .find():

$('button').click(function() {
    var $remaining = $(this).closest('.meaningful').find('.remaining');
    // change text...
});
like image 83
Felix Kling Avatar answered Dec 10 '25 14:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!