Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing the div appended using append method

this is my code...append is working but removing is not working. how to remove the appended div?

<html>
  <head>
    <script type="text/javascript">
      function view(){
        $('body').append('<div class="added"><p>something</p></div>');
      };
      function close(){
        $('.added').remove();
      } ;
    </script>
  </head>
  <body>
    <a onclick="view();">something</a>
    <a onclick="close();">close</a>
  </body>
</html>
like image 268
user1531746 Avatar asked Aug 10 '12 11:08

user1531746


1 Answers

Specify window.close in your html handler:

   <a onclick="window.close();">close<a>

http://jsfiddle.net/ZTwd7/1/

Otherwise close() refers to the native close method, which doesn't do anything.

Here's how you would emulate it with a "javascript" (as opposed to inline html attribute) handler:

elem.onclick = function(event) {
    with(Window.prototype) {
        with(document) {
            with(this) {
                close();
            }
        }
    }
};

This is not exact reproduction (nor does it work in IE etc, that's not the point) but it would put the .close in Window.prototype in front of the global window.close in the scope, so it shadows it. You can still refer to it explicitly with window.close().


You should also totally drop the above and use jQuery instead:

<a id="view">something<a>
<a id="close">close<a>

JS:

$(function() {
    $("#view").click(function() {
        $('body').append('<div class="added"><p>something</p></div>');

    });
    $("#close").click(function() {
        $('.added').remove();

    });
});​

http://jsfiddle.net/ZTwd7/5/


Making an ajax request that fetches a html file to be appended:

$.get("myhtml.html", function(html) {
    $("body").append(html);
}, "html");
like image 119
Esailija Avatar answered Sep 19 '22 20:09

Esailija