I’m trying to select the form element which is the distant parent of a button. The button is deeply nested inside of a div. I have two type of forms in two pages so I’m using the same event for both of them. That’s why I’m using bother the selectors separated by a comma.
$('.createForm, .editForm').on('click', '.delete-btn', function() {
console.log($(this))
});.delete-btn{
background-color: red;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/submit" method="POST" class="editForm">
<div class="form-group">
<div class="d-flex ">
....some elements
</div>
</div>
<div class="form-group">
....some elements
</div>
<div class="form-group">
....some elements
</div>
<div class="form-group">
<div>
<div></div>
<div>
<div class="post-container">
<textarea></textarea>
<button type="button" class="delete-btn">Test</button>
</div>
</div>
<div></div>
</div>
</div>
</form>What I tried so far:
1. console.log( $( this ).parent() ); 2. console.log( $( this ).parent( 'form' ) ); 3. console.log( $( this ).parents() ); 4. console.log( $( this ).parents( 'form' ) ); 5. console.log( $( this ).parentsUntil() ); 6. console.log( $( this ).parentsUntil( 'form' ) ); 7. console.log( $( this ).parent().parent().parent().parent() ); 8. console.log( $( this ).closest( 'form' ) );
Please note that the same jQuery code works when I use an input element instead of a button. Although the input element is one level out of a div than the button.
Advertisement
Answer
This is the correct working code
$('body form').hasClass('.editForm')