Search code examples
jqueryappendpreventdefault

Prevent onclick event of appended element?


I have a page where some onclick code is being added to an appended element and I want to prevent the onclick code from firing.

Here's what I've tried:

$(function() {
  $('.container').append('<div class="appended" onclick="alert(\'DONT DISPLAY\')">CLICK ME</div>');
  
  // Prevent onclick
  $(document).on('click', '.appended', function (e) {
    e.preventDefault();
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

Unfortunately this is not preventing the onclick behavior as desired

EDIT Should have mentioned this, but I don't have access to the code that is adding the onclick event to the HTML, but I am open to removing that attribute if it is possible to do that, after the fact, to an appended element.


Solution

  • One option is to remove the onclick attribute using removeAttr()

    $('.container').append('<div class="appended" onclick="alert(\'DONT DISPLAY\')">CLICK ME</div>');
    
    $('.appended').removeAttr('onclick');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container"></div>

    Doc: removeAttr()