subhojit777
subhojit777

Reputation: 596

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

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?

Upvotes: 1

Views: 1555

Answers (4)

Gabry Gao
Gabry Gao

Reputation: 29

What you need do is you should convert the JavaScript element to a jQuery object.

  1. $(block_element) could convert the JavaScript element to a jQuery object;
  2. contrarily $(block_element)[0] could convert a jQuery object to a JavaScript element.

Upvotes: 1

adeneo
adeneo

Reputation: 318182

$(".remove_item").click(function(){
    $(this).hide("fast", function(){
        var elm = $("#block"),
            parent = $(this).parent(),
            img = $('<img src="/compare/sites/default/files/add_item.jpg" class="image" height="50px" width="50px" />'),
            span = $('<span class="new_item"></span>'),
            new_item = $('<div id="item" name="item" class="div_image"></div>').append(img).append(span);

        elm.remove(parent).append(new_item).on('click', function(){ $(this).parent().remove(); });
});

Upvotes: 0

Starx
Starx

Reputation: 78971

The only thing, you need to change is

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

Rest should work as it is.

Upvotes: 1

You only need to pass the element in the jQuery selector.

First solution (when you append) :

$(block_element).append(new_item);

Second solution (when you select your element)

var block_element = $("#block");

Upvotes: 0

Related Questions