I have a group of buttons, which I’m adding buttons to dynamically. My selection will look something like this:
$elements = [a.midToggle, a.menuToggle, a.ui-crumbs]
I want to prepend this selection to an existing controlgroup:
<div data-role="controlgroup" data-type="horizontal" class="dropZone">
<a href="#" class="some">Some</a>
<a href="#" class="midToggle">MidTog</a>
</div>
However before prepending, I want to remove the buttons already inside the controlgroup from my selection, because otherwise they will be in there multiple times.
I’m trying like this, but it doesn’t work at all:
// I have multiple controlgroups, so I need to add the buttons to all of them
$('.dropZone').each(function() {
var $first = $(this),
$buttons = $elements.clone();
$buttons.each(function() {
// check if class name on new button is already in controlgroup
if ( $(this).is(".midToggle") && $first.find(".midToggle").length > 0 ) {
$(this).remove();
}
if ( $(this).is(".menuToggle") && $first.find(".menuToggle").length > 0 ) {
$(this).remove();
}
if ( $(this).is(".ui-crumbs") && $first.find(".ui-crumbs").length > 0 ) {
$(this).remove();
}
});
// append what's left
$first.append( $buttons )
I figure my $buttons aren’t removed, but I don’t know how to get it to work. Also my three if-statements are kind of lame. Is there a better way to do this?
EDIT:
I had to modifiy the solution a little, because each button has multiple classes, so I cannot simply check for attr(‘class’). This is not perfect, but works:
function clearOut($what) {
$buttons.each(function () {
if ($(this).is($what)) {
$buttons = $buttons.not($what)
}
});
}
// filter for existing buttons
// TODO: improve
if ($first.find('.midToggle')) {
clearOut('.midToggle');
}
if ($first.find('.menuToggle')) {
clearOut('.menuToggle');
}
if ($first.find('.ui-crumbs')) {
clearOut('.ui-crumbs');
}
I shrieked your code into half: