babarosa89
babarosa89

Reputation: 37

How to reference the element that was clicked in the IF statement

How to hide the p that was clicked in the code? Existing new ones?

(function($) {
  $('body').on('click', function(event) {
    if (event.target == $('button')[0]) {
      $('body').append('<p class="myp">text</p>')
    }

    if ($(event.target).attr('class') == 'myp') {
      // hide the clicked p
    }
  })
})(jQuery)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add</button>
<p class="myp">text</p>
<p class="myp">text</p>

Upvotes: 1

Views: 51

Answers (2)

prasanth
prasanth

Reputation: 22500

Why with event.target .Just target with class or id of element to initiate the function

$(document).ready(function() {
  $('#add').on('click', function() {
    $('body').append('<p class="myp">text</p>')
  })
}).on('click', 'p.myp', function() {
  $(this).hide();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>

<p class="myp">text</p>
<p class="myp">text</p>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337570

To make your logic work to detect the p which was clicked, use hasClass(), then hide(), like this:

(function($){
  $('body').on('click', function(event) {
    if (event.target == $('button')[0]) {
      $('body').append('<p class="myp">text</p>')
    }

    if ($(event.target).hasClass('myp')) {
      $(event.target).hide();
    }
  })
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add</button>
<p class="myp">text</p>
<p class="myp">text</p>

However, I presume you're attempting to work with the click event on the body in this manner because the child elements are dynamically generated. As such there's a much better way of achieving what you're doing here; delegated event handlers:

jQuery(function($) {
  $(document).on('click', 'button', function() {
    $('body').append('<p class="myp">text</p>');
  }).on('click', '.myp', function() {
    $(this).hide();
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add</button>
<p class="myp">text</p>
<p class="myp">text</p>

Upvotes: 2

Related Questions