0

I want to remove the parent p tag when the cross button is clicked.

My HTML structure is like this :

jQuery('.delete').click(function() {
  jQuery(this).closest('.question-list').remove()
});

jQuery('.add-question-btn').click(function() {
jQuery("#add-question-div-parent").append("<p class='add-question-div' style='position: relative'><input type='text' class='add-ques-text' placeholder='Add Question'><span><i class='fa fa-times cls' aria-hidden='true'></i></span></p>");
});
        
jQuery('.cls').click(function() {
   jQuery('.add-question-div').remove()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<p class="question-list">Here is my question.Here is my question.Here is my question.
 <span><i class="fa fa-times delete" aria-hidden="true"></i></span>
</p>
<div id="add-question-div-parent" class="full-width"></div>
<button class="add-question-btn">+</button>

.add-question-div this has been added successfully after '.add-question-btn' button has clicked, but unfortunately i'm not able to remove .add-question-div when i click on .cls.

Any kind of help would be highly appreciated. Thanks.

Akhil Aravind
  • 5,741
  • 16
  • 35

1 Answers1

0

The .cls element is added dynamically so the click event is not associated at the time of page load so use $(document).on('click','.cls', function(){...});. You also need to delete the particular add-question-div when the icon is clicked so use $(this).closest('.add-question-div').remove();

$('.delete').click(function() {
  $(this).closest('.question-list').remove()
});

$('.add-question-btn').click(function() {
$("#add-question-div-parent").append("<p class='add-question-div' style='position: relative'><input type='text' class='add-ques-text' placeholder='Add Question'><span><i class='fa fa-times cls' aria-hidden='true'>X</i></span></p>");
});

$(document).on('click','.cls', function() {
   $(this).closest('.add-question-div').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="question-list">Here is my question.Here is my question.Here is my question.
  <span><i class="fa fa-times delete" aria-hidden="true"></i></span>
</p>
<div id="add-question-div-parent" class="full-width"></div>
<button class="add-question-btn">+</button>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62