Search code examples
jqueryformshtmlinputtraversal

JQuery how to traverse to <form> from <button> inside, with <div> in between


Alright guys, so I have the below structure, 10 times, which means 10 forms. $('button') will handle event for any button, as you know.

<div>
  <form ...>
    <div><button type='button'>Submit</button></div>
    <div><input /></div>
    <div><input /></div>
    <div><input /></div>
    <div><input /></div>
  </form>
</div>

Using JQuery only, and its traversing methods only, how do I get the <form> from $(this) when I click on the button??

I used a mix of parent(), prev(), etc before but couldn't get it. For example, $(this).closest('form').nodeName gives "undefined" in alert popup.


Solution

  • use

      $(':button').closest('form')
    

    UPDATE

    $(':button').click(function(){
        alert($(this).closest('form').attr('class'));
    });