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.
JavaScript
x
3
1
$('.createForm, .editForm').on('click', '.delete-btn', function() {
2
console.log($(this))
3
});
JavaScript
1
3
1
.delete-btn{
2
background-color: red;
3
}
JavaScript
1
32
32
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<form action="/submit" method="POST" class="editForm">
3
4
<div class="form-group">
5
<div class="d-flex ">
6
some elements .
7
</div>
8
</div>
9
10
<div class="form-group">
11
some elements .
12
</div>
13
14
<div class="form-group">
15
some elements .
16
</div>
17
18
<div class="form-group">
19
<div>
20
<div></div>
21
22
<div>
23
<div class="post-container">
24
<textarea></textarea>
25
<button type="button" class="delete-btn">Test</button>
26
</div>
27
</div>
28
29
<div></div>
30
</div>
31
</div>
32
</form>
What I tried so far:
JavaScript
1
14
14
1
1. console.log( $( this ).parent() );
2
2. console.log( $( this ).parent( 'form' ) );
3
4
3. console.log( $( this ).parents() );
5
4. console.log( $( this ).parents( 'form' ) );
6
7
5. console.log( $( this ).parentsUntil() );
8
6. console.log( $( this ).parentsUntil( 'form' ) );
9
10
7. console.log( $( this ).parent().parent().parent().parent() );
11
12
8. console.log( $( this ).closest( 'form' ) );
13
14
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
JavaScript
1
2
1
$('body form').hasClass('.editForm')
2