Get all the IDs of the elected ones in jQuery

3

Well I remove the CSS of a certain element like this:

$('#menu' + this.id + '').removeClass('open');

What I need to do and remove from all elements #menu less than informed.

I tried to do this:

!$('#menu' + this.id + '').removeClass('open');

But it did not work.

I have several #menu as #menu1 , #menu2 . Being that they do not repeat themselves in html. I need to remove the CSS from everyone, less than% informed%.

Does anyone know how to do this?

    
asked by anonymous 14.07.2017 / 14:18

2 answers

3

You can use not :

$('div[id^=menu').click(function() {
  // indica qual item não deve ser removido
  $('div[id^=menu').not($(this)).removeClass('open');
  visualizar();
});

// apenas visualizacao
function visualizar() {
  $('div[id^=menu').each(function() {
    console.log($(this).attr('id'), $(this).attr('class'));
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="menu1" class="open">1</div>
<div id="menu2" class="open">2</div>
<div id="menu3" class="open">3</div>
    
14.07.2017 / 14:26
1

You can use .toggleClass(classe, condição) by passing the ID check to see if you should add or remove the class.

Example:

var idEspecial = 'menu1';
$('div[id^=menu').each(function() {
  $(this).toggleClass('open', this.id === idEspecial);
});
div {
  color: black;
}

.open {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="menu1" class="open">1</div>
<div id="menu2" class="open">2</div>
<div id="menu3" class="open">3</div>
    
14.07.2017 / 14:31