11

I want to find the next form-element, starting from input-object inside. Find() is a great function to find child objects. But what about the opposite Way to find in parent?

<form id="grabbMe">
    <div>
        <div>
            <div>
            <div><input type="text" value="test"></div>
            </div>
        </div>
    </div>
</form>

<script>
    $('input').findUp('form').attr('id')
</script>
dazzafact
  • 2,570
  • 3
  • 30
  • 49

2 Answers2

18

You can use jQuery's closest() function to do this.

$('input').closest('form').attr('id');
kfuglsang
  • 2,385
  • 2
  • 21
  • 26
8

The opposite of find() is parents().

closest() isn't quite an opposite to find(), although depending on what you're trying to do, it may work for you.

the find() function finds all occurances of the selector within the descendants of the element you specify.

closest() only finds the first occurrence of the selector, going upward through the ancestors of the specified element.

So the correct opposite to find() would be parents(), which will find all ancestors of your element that match the specified selector.

Skeets
  • 4,476
  • 2
  • 41
  • 67