Delete dynamically created tab and panel?

Delete dynamically created tab and panel?

Hi folks,

I have exhaustively searched this topic, and none of the proposed solutions seems to work. I'm dynamically creating ui ajax tabs, and I want users to be able to delete them. It's easy to create a function that deletes the currently selected tab, because it has a class of ".ui-tabs-active" by default. But the currently selected tab panel doesn't get a class to target. So how do I do this?

Here's my code:

$(function() {
  var $tabs = $('#nav-tabs').tabs();
  $('.add-tab').click(function(e) {
    e.preventDefault()
    var tabName = $(this).text(),
tabLink = $(this).attr('href'),
      tabNumber = -1;
    $tabs.find('.nav-tab-menu li a').each(function(i) {
      if ($(this).text() == tabName) {
        tabNumber = i;
      }
    });
    if (tabNumber >= 0)
      $tabs.tabs("select", tabNumber)
    else {
      $("<li><a href=" + tabLink + ">" + tabName + "</a><span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>")
        .appendTo(".nav-tab-menu");
      $("#nav-tabs").tabs("refresh");
 $('#nav-tabs').tabs('option', 'active', -1);
    }
// Delete the tab on click
$(document).on( 'click', '.ui-icon-close', function( event ) {
$(this).closest('li.ui-tabs-active').remove()
return false
});
})
});

Here's an example page: