Search code examples
javascriptjqueryevent-handlingdynamically-generatedevent-delegation

Target dynamically added element using jQuery


I know how to use evenet Delegation on jQuery. To listen an even on dynamically added element I have to use following..

$('body .some-class').on('click', '.dynamically_added_ele', function(){});

I understand it quite. Come to actual problems. Suppose I have a button and DOM element which I want to add on document dynamically.

<button class="my-button">Click Me</button>
var newDom = '<p class="new-dom">Hello there I am new content</p>';

Now I am binding click event on button to create new element

var allow = true;
$('.my-button').on('click', function(){
    var newDom = '<p class="new-dom">Hello there I am new content</p>';
    if( allow ) {
       $(this).after($(newDom));
    } else {
        $(newDom).remove(); // Not removing the new added element. Can't target that newly added element
    }
    allow = false;
});

variable allow will check to be true then jQuery will create that element and last allow variable will be false. When again use click that button allow will be false and that time jQuery should remove the newly added element. But here I am facing the problems. I am not able to remove that newly added element like what I have coded above.

What can I do now?


Solution

  • Maybe like this:

    var allow = true;
    var newDom = $('<p class="new-dom">Hello there I am new content</p>');
    
    $('.my-button').on('click', function(){
        if( allow ) {
           $(this).after(newDom);
           allow = false;
        } else {
            newDom.remove();
            allow = true;
        }
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    
    <button class="my-button">Click Me</button>