SO is full of Monkeys
SO is full of Monkeys

Reputation: 319

dynamically added class can't be called

I am trying to accomplish delete in page which is filled with data by ajax call. my page has this before data is loaded:

<span id="ShowSelectedCategories"></span>

and after ajax call i fill with below info:

function(data){
    $('#ShowSelectedCategories').prepend('<a href="" id="'+b.SelectedCategoriesID+'" class="DeleteCat"> x <span style="color:red">' + data +'</span> </a>&nbsp ');
}

and finally after click i want to remove clicked element but it doesn't work.

$(function(){

    $("#ShowSelectedCategories").click(function(e){
    e.target.outerHTML //this is the part i want to remove after click

e.preventDefault();
    })

I have tried $(".DeleteCat).click() but this gave error because elements with that class was created dynamically.

Your help is appreciated

Upvotes: 4

Views: 264

Answers (3)

vani saladhagu
vani saladhagu

Reputation: 184

Use something like this to call dynamically added class

$('.class').live("click", function(){

  $('#id').remove();   


});

Upvotes: 1

Adil
Adil

Reputation: 148120

Try $(e.target).remove(),

$("#ShowSelectedCategories").click(function(e){
         $(e.target).remove();    
         e.preventDefault();
});

If you want to delete element with class DeleteCat within span with id ShowSelectedCategories then you can do it like this,

$("#ShowSelectedCategories").on("click", "DeleteCat" function(e){
         $(this).remove();    
         e.preventDefault();
});

Upvotes: 5

Shmiddty
Shmiddty

Reputation: 13967

$('#ShowSelectedCategories').on('click', '.DeleteCat', function(e){
    $(this).remove();
    e.preventDefault();
});

http://jsfiddle.net/Dj5NQ/

Upvotes: 2

Related Questions