Search code examples
jqueryjquery-selectorsdom-traversal

jQuery Get the original context from a find


If I want to fetch a form, then grab some button, then attach some action to that button that submits my form, I'm currently doing it like so:

<form>
  <button>Some Button</button>
</form>

$('form').find('button').click(function(){
  $(this).closest('form').submit();  // is there a better way of getting the form?
});

I'm wondering if there's a more performant way of selecting the original form element within my find. Instead of having to traverse back up the dom, is there any way to get the reference to my original form object inside the click event of its decendant?

Unfortunately .context will give me the button element in this case, any way i can get the original context? Or do I just have to traverse up?

Note that this is a contrived example, i'm not actually using buttons and forms, but I'm more interested in fetching the original context within a find.


Solution

  • I think the point is to cache the first call? Just run it through an each(), which will allow you to store context in that's method's parameters.

    $('form').each(function(idx,el){
       $(this).find('button').click(function(){
          $(el).submit();  
       });
    });