Reputation: 20250
I'm struggling to understand why a jQuery object can't be appended more than once:
var $divObj = $('<div/>', { 'text': 'This is a div!' });
$('button').on('click', function() {
$('#example').append($divObj);
});
<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.
Upvotes: 2
Views: 703
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
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