How to select an element in a jQuery selection

Asked

Viewed 910 times

2

For example, I have the following code:

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

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

$els.find('.active');

But it didn’t work, because the method find search for child elements. I have not tried the method siblings because I have more than one selected element and they are not necessarily "brothers".

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

2 answers

2


In that case you use filter:

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

Now, if you sail with next and prev from the $el, will be sailing for his brothers in the DOM, not in your original list $els.

  • It’s true, I’d forgotten the filter. Because then bfavaretto, I already imagined it of the navigation. I noticed that in the object $el has the object prevObject which is the previous list, if I have the $el to do the navigation. How to catch it?

  • Look at this: https://jsfiddle.net/ndc1nryh/1/

  • You go back to the previous list with the end – https://jsfiddle.net/ndc1nryh/2/

  • True. I added an answer with this part, I will complement...

0

Complementing the answer, on how to navigate between the elements:

Suffice:

  • Grab the previous object: $el.prevObject $el.end() (as mentioned by @bfavaretto)
  • Grab the selected object index: $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>Item 1 1</li>
<li>Item 1 2</li>
<li>Item 1 3</li>
<li>Item 1 4</li>
<li>Item 1 5</li>
</ul>
<ul>
<li class="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>

  • I think prevObject was designed as an internal jQuery method, so much so that it is not in the documentation. Better use the end even.

  • And beware of the index, if I am not mistaken it returns the index of the object in relation to the parent object in the DOM, not in relation to its selection.

  • I updated the code, put the first element on the second list to test, and the previous object selected was the last one on the first list. @bfavaretto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.