billyonecan
billyonecan

Reputation: 20250

Why can't a jQuery object be appended more than once?

I'm struggling to understand why a jQuery object can't be appended more than once:

jQuery

var $divObj = $('<div/>', { 'text': 'This is a div!' });

$('button').on('click', function() {
  $('#example').append($divObj);
});

Markup

<div id="example"></div>
<button>Add Div</button>

This only works the first time the button is clicked. Subsequent clicks don't appear to do anything.

I know that I can use clone() when appending the object, or can pass the div as a string, but I'm looking for an explanation as to why appending an object doesn't work more than once.

Here's a sample fiddle

Upvotes: 2

Views: 703

Answers (2)

Maclane
Maclane

Reputation: 67

The problem is that after total loading of the page it is not taking the value from $divObj.
If you want to show the message every time you click what you can do is to put the $divObj inside on click function and it will work.
Here is the code changes.

$('button').on('click', function() {
    var $divObj = $('<div />', { 'text': 'This is a div!' });
    $('#example').append($divObj);
}); 

Thanks

Upvotes: 0

James Allardice
James Allardice

Reputation: 165951

Because $divObj holds a reference to a DOM element (well, a jQuery object, but that just wraps the DOM element). When you append that element to the DOM, $divObj still refers to that same object. It doesn't magically duplicate it when you insert it into the DOM.

As you said, you can use .clone() to create a new copy of the node, which can be appended again in its own right.

Upvotes: 7

Related Questions