How to remove an element created using jquery?

I wrote this block of code in jquery to create three elements after some events

$('body').append(
tmp= $('<div id="tmp"></div>')
);

$('<div id="close" />').appendTo("#tmp");   
$('<div id="box-results" />').appendTo('#tmp');

these three elements are created normally and added to my DOM, but I want to remove them using some function, for example:

$("#close").click(function(e){

e.preventDefault();
$("#tmp").remove(); 
//$("#overlay").remove(); 
});

and after I click close, a div notification will occur. what happened to my code?

here is an online example: mymagazine.ir/index.php/main/detail/36 - please find the sentence "here jquery issue" on the site, because the language of the site is Persian

+5
source share
3 answers

you need to add a click handler on #close after inserting the element into the document.

, ; ff36:

<html>
<head>
 <title>whatever</title>
 <style type="text/css">
   div {
     border: 1px solid black;
     padding: 0.3em;
   }
 </style>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
 <script type="text/javascript">
  $(document).ready(function ()
  {
    $('body').append($('<div id="tmp"/>'));
    $('<div id="close">click me</div>').appendTo("#tmp");   
    $('<div id="box-results">contents</div>').appendTo('#tmp');
    $('#close').bind('click', function ()
    {
      $('#tmp').remove();
      return false;
    });
  });
 </script>
</head>
<body>
</body>
</html>

$.ajax({
    ...
    success: function ()
    {
        $('<div id="close"/>').appendTo($('#tmp'));
    }
});
$('#close').click(function (e) ...);

$.ajax({
    ...
    success: function ()
    {
        $('<div id="close"/>')
            .click(function (e) ...)
            .appendTo($('#tmp'))
        ;
    }
});
+11

#tmp #close , click , live():

$("#close").live('click', function(e){    
  $("#tmp").remove(); 
  return false;
});

live() :

, , .

, ( ), .

+3

You should use a live method instead of a click. This will allow you to add / remove elements without changing their behavior.

$("element").live("click", function() { /*do things*/ });
+2
source

All Articles