I have the following HTML:
The problem is that replaceWith
returns the removed element, not the new element. I suggest a different path:
$(function() {
var cond1 = $('#condition_value_1');
var cloned_cond1 = cond1.clone().removeAttr('style');
var cond1_select = '';
$('#showme').click(function() {
cond1.replaceWith(cond1_select);
$("#condition_value_1").select2({
placeholder: 'Select choice'
});
cond1 = $("#condition_value_1");
});
$('#clickme').click(function() {
if ($('#condition_value_1').hasClass('select2-hidden-accessible')) {
$("#condition_value_1").select2('destroy');
}
$('#condition_value_1').replaceWith(cloned_cond1);
cond1 = $('#condition_value_1');
});
});
Note that I've removed the attribute from the clone before ever replacing anything; that way, you don't have to worry about it.
Note also in the showme
click handler, we replace the HTML, then get a new hook to $("#condition_value_1")
. That's because cond1
is no longer in the DOM, since you've replaced it with the HTML in the first line.
Likewise, in the clickme
click handler, you need to reset the value of cond1
to match your new HTML.