I have a global variable var $test = $('#test'); where #test id of div that initially exist in DOM. If i remove the div with remove() and append it again then the global variable $test no longer recognizes the the newly appended div with id #test. What am i doing wrong. Why does this happen?
I have a global variable var $test = $(‘#test’); where #test id of div
Share
Instead of creating a new element from the string, just append the original element:
Example: http://jsfiddle.net/mr3C4/5/
That way your handler is still referencing the same element you have referenced in the
$testvariable.This is because
$testis referencing a specific jQuery object that references a specific element, which is no longer part of the DOM. You were recreating an idential element from a string in your original code.…or you can use the
detach()[docs] method instead of theremove()[docs] method if you want to keep jQuery data associated with it.Example: http://jsfiddle.net/mr3C4/6/
EDIT:
If you want to update your element, it is better to use the method above, and make modifications to the original.
If you can’t do that because you’re making a change that can’t be made to the original, like changing the
tagName, then create your new element, and update your variable.You could even keep the same jQuery object, and just update the element: