0

I want to delete the paragraph that jquery create when I click the paragraph.

<p class="test">cutsom event</p>
<button class="clcik">click</button>

jquery:

$(function () {
"use strict";

$(".test").on("click", function () {
    $(this).hide();
});

$("button").on("click", function () {
    $("<p>delet this paragraph</p>").insertAfter($(this));
});

$("p").on("click", function () {
    (this).hide();
});
});

update: @LinkinTED solved it, but dose there best practice for for that code?

akram
  • 71
  • 6

2 Answers2

6

When you call this:

$("p").on("click", function () {
    $(this).hide();
});

your paragraph doesn't exist yet, so this doesn't actually do anything.

You can do $('body').on('click','p', function(){}) instead

LinkinTED
  • 16,671
  • 4
  • 27
  • 53
TKoL
  • 10,782
  • 1
  • 26
  • 50
  • console said this Uncaught TypeError: "p".hide is not a function when i put this `$('body').on('click', 'p', function () { ("p").hide(); });` – akram Oct 06 '17 at 09:27
  • You are forgetting the `$` (again) `$("p").hide();` – LinkinTED Oct 06 '17 at 09:31
1

Your function will work on the paragraphs that are static in the page. However the dynamic added paragraphs won't. You'll need to bind the function on a static element.

$(function () {
  /* obsolute while the last function is the same 
  $(".test").on("click", function () {
    $(this).hide();
  });*/

  $("button").on("click", function () {
    $("<p>delet this paragraph</p>").insertAfter($(this));
  });

  $(document).on("click", "p", function () {
    $(this).hide();
//  ^------ you forgot the $ here
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="test">cutsom event</p>
<button class="click">click</button>
LinkinTED
  • 16,671
  • 4
  • 27
  • 53