JQuery find() opposite
Asked Answered
B

2

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>
Birnbaum answered 22/1, 2012 at 13:42 Comment(0)
K
18

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

$('input').closest('form').attr('id');
Kondon answered 22/1, 2012 at 13:44 Comment(0)
K
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.

Keaton answered 5/12, 2018 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.