1

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?

4 Answers 4

1

The only thing, you need to change is

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

Rest should work as it is.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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");

1 Comment

Second solution will break removeChild.
0
$(".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(); });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.