Adding items to accordion/losing CSS

Adding items to accordion/losing CSS

This may be obvious to some of you but took me a bit of time to figure out.

In some situations you may need to dynamically add an accordion "shelf", for example, your accordion represents different groupings and in some other place in the UI you have a field to add a new group.

Somewhere in your HTML, you may have something like:
<div id="accordion">
        <div id="shelf_1">
                <h3><a href="#"></a></h3>
                <div>
                        <ul>
                                <li>Item 1</li>
                                <li>Item 2</li>
                                <li>Item 3</li>
                                ...and so on...
                        </ul>
                </div>
        </div>
</div>

You would obviously generate <div> items such as "shelf_1" for each group using PHP or Javascript or what not. Very often these items would be "skinned" or at least loosely styled by CSS.

Now, if you wanted to add a shelf using Javascript, you would do something like:

var item = '<div><h3><a href="#" >Group Name Here</a></h3>';
item += '<div><ul><li><a href="#">First Item</a></li></ul></div></div>';
...etc...
$('#accordion').append(item);

If you try to do the above, you'll notice it adds the shelf but doesn't have the same CSS formatting as the rest of the control.

Quickly browsing the docs, you notice a method called "destroy", and this turns out to be half the answer...as it forces the accordion to be recreated.

The trick, however, is to re-init the accordion after that! Again, this may be totally obvious to some but I had assumed destroy() would take care of it. So try:

$('#accordion').append(item).accordion('destroy');
$('#accordion').accordion(accordOptions);                                   

where accordOptions = { accordion option array }

Hope this helps.
Cheers!
--Avital