0

I have some paragraphs in my html as an example, and when I click on it, the JQuery click activates correctly and executes de function. However, I have a button that adds new paragraphs to de body but the new ones do nothing on click and I don't know why:

My html body

        <h1> Test </h1>
        <input type="text" id="newP" value="New paragraph">
        <button id="add"> Add </button>
        <p> Paragraph 1 </p>
        <p> Paragraph 2 </p>

My js file

$(document).ready(function(){

$("p").click(function(){
    console.log("Hello");
    this.remove();
});
$("#add").click(function(){
    $("#add").after("<p> " + $("#newP").val() + "</p>");
});
});

The 2 example paragraphs delete correctly and shows "Hello" but de new ones don't. I want to do something more complicated than just deleting them so I need to know why the function isn't working for them. (I must use JQuery)

  • Not exactly, because it must be with jquery. Its for a class exercise – Carmen Sirgo Nov 28 '19 at 16:31
  • There is a jquery version in the accepted answer. You can replace `$(document)` with the parent element of where your dynamic elements appear if you want, or leave as is. – mark_b Nov 28 '19 at 16:37

1 Answers1

1

The reason is that you add new click listeners before adding new elements. You can use the three-argument form of the click handler it will apply also to new elements added.

$(document.body).on('click', '#add', function(){
    $(this).after("<p> " + $("#newP").val() + "</p>");
});

Another issue might be that you have multiple elements with the same id. You should give them css classes like add and then select for .add.

Adder
  • 5,708
  • 1
  • 28
  • 56