February 27, 2012

how to append a div tag generated by jQuery dynamically with a javascript div tag element

Question by subhojit777

I want to append a div tag generated by jQuery dynamically with a javascript div tag element. My code looks like this:

$(".remove_item").click(function(){
  $(this).hide("fast", function(){
  var id = $(this).parent().attr("id");
  var remove_item_id = document.getElementById(id);
  var block_element = document.getElementById("block");

  block_element.removeChild(remove_item_id);

  new_item = $("<div/>");
  new_item.attr("id", "item");
  new_item.attr("name", "item");
  new_item.addClass("div_image");
  new_item.append($("<img/>")
  .addClass("image")
  .attr("src", "/compare/sites/default/files/add_item.jpg")
  .attr("height", 50)
  .attr("width", 50));

  new_item.append($("<span/>")
  .addClass("new_item")
  .click(function(){
  $(this).parent().remove();
  }));

  block_element.append(new_item);
});
});

The code for appending the jQuery div tag with javascript div tag should look like this:
block_element.append(new_item);

But its giving error since we cannot bind since I am using javascript and jQuery in the same line. Is there any way to do it?

Answer by Starx

The only thing, you need to change is

var block_element = $("#block");
$("#"+remove_item_id).remove();

Rest should work as it is.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!