Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery find() opposite

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>
like image 257
dazzafact Avatar asked Jan 22 '12 13:01

dazzafact


2 Answers

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

$('input').closest('form').attr('id');
like image 139
kfuglsang Avatar answered Sep 22 '22 13:09

kfuglsang


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.

like image 39
Skeets Avatar answered Sep 25 '22 13:09

Skeets