0

What do I use as an alternative to the .siblings() method in jQuery to traverse over divs of a particular class but in separate div containers?For something like this to work:

HTML:

<div id="container1">
   <div id="1"></div>
</div> 

<div id="container2">
   <div id="2"></div>
</div> 

JS:

$('#1').addClass('selected');

$('.selected').on('click',function() {
    alert('hi');
});

$('#2').addClass('selectable');

$('.selectable').on('click',function() {
   $(this).addClass('selected')
          .removeClass('selectable')
          .siblings('.selected')
          .off('click');
});
RB.
  • 36,301
  • 12
  • 91
  • 131
Ronophobia
  • 349
  • 3
  • 16

2 Answers2

1

I'd code this a different way:

EDIT:

$('#1').addClass('selected');
$('#2').addClass('selectable');

var $outerContainer = $('#container1').parent();
$outerContainer.on('click','.selected,.selectable', function(event) {
    if ($(event.target).is(".selected")) {
        alert('hi');
    } else {        // .selectable
        $('.selected', $outerContainer)
            .removeClass('selected')
            .addClass('selectable');
        $(event.target)
            .addClass('selected')
            .removeClass('selectable');
    }
});

Here's a link to jsfiddle

marty
  • 4,005
  • 22
  • 19
  • Ah no this makes the .selectable element alert on click. http://jsfiddle.net/93Cvx/3/ – Ronophobia Mar 20 '13 at 11:38
  • @Ronophobia, ahh, yes, I had been neglecting the fact that the propagated event would come last. See my edited post. – marty Mar 20 '13 at 12:04
1

May be this might help:

$('.selectable').on('click',function() {
   $(this).addClass('selected')
          .removeClass('selectable')
          .parent()
          .siblings()
          .children()
          .off('click');
 });
Jai
  • 74,255
  • 12
  • 74
  • 103