views:

124

answers:

2

Hello,

I have this code currently in one of my websites,

$("a.navlink").click(function (ev) {
       ev.preventDefault();
       var id = $(this).attr("id")
       if($(this).hasClass("active")) {
        alert(id);
        $(id).remove("<div id="+ id +"/>");
       }
      $(this).toggleClass("active");
         var url = $(this).attr("href");
          $.ajax ({
              url: "index.php/home/category",
              type: "GET",
              success : function (html) {
       //alert("Success");
                  $("#accordion").append($("<div id="+ id +"/>").append(html)
         );
              }
          });
      });

Essentially what is does it gets the ID from the click nav and gets some data from the database and then places that data in a div that is uniquely named with the ID of the click element. What I want to know is how could then remove the div element that is created on the fly, as you can see from my code I have given it try.

+2  A: 
if ($(this).hasClass("active")) {
   $(this).remove();
}

Is all you need!

altCognito
isnt this is representation of the link rather than the div?
sico87
Sure, and that's what you're getting the ID of according to this code. (see my comment to your main question) If you want the ID of a child DIV, then you need to do something different in your code.
altCognito
i get the ID of (this) but only so I can assign it as class(was an id) to the div that is appended to #accordion
sico87
+2  A: 

You have another problem with your code. You are attempting to give the DIV the same ID as the link. IDs need to be unique so this results in invalid HTML. Try prepending "div_" to the link's id, then use:

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

resulting in:

$("a.navlink").click(function (ev) {
    var id = $(this).attr("id");
    if($(this).hasClass("active")) {
        alert(id);
        $('#div_' + id).remove();
    }
    $(this).toggleClass("active");
    var url = $(this).attr("href");
    $.ajax ({
        url: "index.php/home/category",
        type: "GET",
        success : function (html) {
            //alert("Success");
            $("#accordion").append($("<div id='div_"+ id +"'/>").append(html));
        }
    });
});
tvanfosson