How to select an element in a jQuery selection

3

For example, I have the following code:

var $els = $('elementos'); // cerca de 8 elementos selecionados

Then from this group of elements, I want an element that has the class active . I tried something like:

$els.find('.active');

But it did not work, because the find method looks for child elements. I have not tried the siblings method since I have more than one element selected and they are not necessarily "siblings".

How to find a certain element in this group and then be able to navigate between them as next() and prev() , is it possible?

    
asked by anonymous 17.07.2015 / 20:08

2 answers

3

In this case you use filter :

var $els = $('elementos');
var $el = $els.filter('.active');

Now, if you navigate with next and prev from $el , you'll be browsing through his siblings in the DOM, not in your original $els list.

    
17.07.2015 / 20:10
0

Complementing the answer, about navigating between elements:

Enough:

  • Catch the previous object: $el.prevObject $el.end() (as mentioned by @bfavaretto )
  • Get the index of the selected object: $els.index($el)
  • Navigate between them: $el.prevObject[$els.index($el)-1] or $el.prevObject[$els.index($el)+1]
  • Navigate between them: $el.end()[$els.index($el)-1] or $el.end()[$els.index($el)+1]

$els = $('li');
$el = $els.filter('.active');


$prev = $( $el.end()[$els.index($el)-1] );
$next = $( $el.end()[$els.index($el)+1] );

$('.prev').text('Anterior: ' + $prev.text() );
$('.el').text( 'Ativo: '     +  $el.text()  );
$('.next').text( 'Próximo: ' + $next.text() );
.active{
   color: #2376D0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><ul><li>Item11</li><li>Item12</li><li>Item13</li><li>Item14</li><li>Item15</li></ul><ul><liclass="active">Item 2 1</li>
<li>Item 2 2</li>
<li>Item 2 3</li>
<li>Item 2 4</li>
<li>Item 2 5</li>
</ul>
<div class="prev"></div>
<div class="el"></div>
<div class="next"></div>
    
17.07.2015 / 20:34