1

I add a class in a div with .append() but when i click on the class (.again), nothing happens (When I click on How are You ? Fine ! should display). Do you have an idea ?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="src">
  <p class="feedback">Welcome !</p>
</div>

<script>
$('.feedback').click( function() {
  $('.feedback').html( 'Thank You ! Do not click here ;) click on How are you below');
  $('#src').append('<p class="again">How are you ?</p>');
});

$('.again').click( function() {
  $('.again').html( 'Fine !');
});

</script>
zeuf
  • 400
  • 3
  • 10

2 Answers2

3

It is not working because you are attaching the event click of the class "again" before you create the element with that class.

The $('.again') return all the elements that have that class in the document in that moment.

For doing what you need you should attach the event on the class after you create the element. Something like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="src">
  <p class="feedback">Welcome !</p>
</div>

<script>
$('.feedback').click( function() {
  $('.feedback').html( 'Thank You ! Do not click here ;) click on How are you below');
  $('#src').append('<p class="again">How are you ?</p>');

  $('.again').click( function() {
    $('.again').html( 'Fine !');
   });
});

</script>
Brank Victoria
  • 1,447
  • 10
  • 17
1

You add a new element to which the old processing function is not bound.

 $('.feedback').click( function() {
  $('.feedback').html( 'Thank You ! Do not click here ;) click on How are you below');
  $('#src').append('<p class="again">How are you ?</p>').click( function(){  $('.again').html( 'Fine !')});;
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div id="src">
  <p class="feedback">Welcome !</p>
</div>
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17