The question has changed completely based on new information and comments, so will add an appropriate answer here instead (my other answer is now deleted).
The specific problem is that you wish to clone jQuery UI collapsible objects already on the page.
Unfortunately jQuery UI attaches to existing collapsible objects (decorated with data-role="collapsible
) at document load time, in doing this it also creates a dynamic structure on each item to manage the open and closed states.
It also stores state data referencing the new pieces of the collapsible element. This means that when it is clicked it will reference the original child elements of the cloned item (not the clone).
A clone has more elements than you expect, so you cannot just reapply collapsible() to them.
- If you deep clone a collapsible element, it incorrectly references the original element's components and toggles that one instead of itself.
- If you shallow clone a collapsible element you get additional structure that needs to be undone/removed before you can apply
collapsible()
. otherwise you get this result:

So the options are:
- Find out how to attach a new code instance without changing the structure (hard)
- Undo the structure changes and reapply collapsible (easier)
To do the second of these, first we look at what collapsible
does to elements:
Element before collapsible:
<div class="cloneme" data-role="collapsible">
<h1>Click me - I'm collapsible!</h1>
<p>I'm the expanded content.</p>
</div>
Element after collapsible:
<div class="cloneme ui-collapsible ui-collapsible-inset ui-corner-all ui-collapsible-themed-content ui-collapsible-collapsed" data-role="collapsible">
<h1 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-icon-plus ui-btn-icon-left ui-btn-inherit">Click me - I'm collapsible!<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h1>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<p>I'm the expanded content.</p>
</div>
</div>
Answer "undo and reapply":
The code to do all this is:
$(function () {
var clone = $(".cloneme").clone();
$('.ui-content').append(clone);
clone.addClass('ImAClone'); // Just for testing - REMOVE THIS
clone.find('.ui-collapsible-heading-toggle').children().unwrap();
clone.find('.ui-collapsible-heading-status').remove();
clone.find('.ui-collapsible-content').children().unwrap();
clone.collapsible();
});
You can probably combine some of the operations into a single one (e.g. the unwraps), but I leave that for you to do :)
Thoughts: Ideally these plugins would allow for applying to an existing element that already has collapsible decorations.
The end result is two independent collapsible elements:
