1

i'm having 2 buttons one to create a div and the other is to remove the added div. There's no problem adding a new div but when i try to remove it i can't use div:eq(index) because it wasn't loaded with the DOM here's the code

$(document).ready(function(e) {

$(".inner").eq(1).css("background-color","#0C9");
$(".inner").eq(2).css("background-color","#F00");
$(".inner").eq(3).css("background-color","#990");

$("#add").click(function(){
    $(".content").append("<div class='inner'><a href='#' class='rem'>remove this inner</a></div>"); 
});

$(document).on("click","a.rem",function(e){
    e.preventDefault();
    var num = $("a.rem").index(this);
    //alert(num);
    $(".inner").eq(num).remove();
});
});
</script>

code on jsfiddle : http://jsfiddle.net/7uzSv/3/

jq beginner
  • 1,010
  • 3
  • 21
  • 41

4 Answers4

1
$('.content').on('click', 'a.rem', function(e){
  e.preventDefault();
  $(this).closest('.inner').remove();
});

This is a bit of a different solution, but in my opinion is more effective.

Fiddle: http://jsfiddle.net/7uzSv/2/

ahren
  • 16,803
  • 5
  • 50
  • 70
  • thanks but why did colors change ? i don't see any change in the code except $(this).closest('.inner').remove(); ? – jq beginner Jun 28 '13 at 14:26
  • They changed because of your first few lines of code that initially set the `backgroundColor` of `.inner` elements. – ahren Jun 28 '13 at 14:27
  • aha you have added the inner divs manually i'm not lloking for this i want to add them by clicking the add button – jq beginner Jun 28 '13 at 14:29
  • @jqbeginner - You can still add them dynamically and the above code would work to remove them. I added them manually so you could clearly see that it was the specific `.inner` element that was being removed, since you could distinguish them by color. – ahren Jun 28 '13 at 14:31
0

There is no meaning that removing an element,which is not exists.

So check for existence

  var num = $("a.rem").index(this);
  var checker= $(".inner").eq(num);

if(typeof checker !== 'undefined' && checker !== null) {
    $(".inner").eq(num).remove();
  }
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Once try this,

$("#add").on("click",function(){
        $(".content").append("<div class='inner'><a href='#' class='rem'>remove this inner</a></div>"); 
    });
$(document).on("click","a.rem",function(e){
    e.preventDefault();
    $(this).parent('.inner').remove();
    });

jsfiddle

Mahesh.D
  • 1,691
  • 2
  • 23
  • 49
0
$("#add").click(function(){
    $(".content").append("<div class='inner'><a href='#' class='rem'>remove this inner</a></div>");

$(".inner").eq(1).css("background-color","#0C9");
$(".inner").eq(2).css("background-color","#F00");
$(".inner").eq(3).css("background-color","#990");

});

$(document).on("click","a.rem",function(e){
    e.preventDefault();
    var num = $("a.rem").index(this);
    $(".inner").eq(num).remove();
});
jq beginner
  • 1,010
  • 3
  • 21
  • 41