shriek
shriek

Reputation: 5843

Getting the element on each iteration.

I have a list which may or may not be displayed on the screen. What I have to do now is check whether all the li in that list is visible or not. If the li indeed is visible then I want the iteration to stop and then get that particular element.

My attempt:-

var getList = $("ul li").each(function(){
                                    return $(this).is(":visible") ? false: true; 
                                    });

From my understanding what the above code is, it gets the array from the "ul li" selector and iterates with the function each. I need to break the iteration whenever I notice that the element is visible so the false is returned to get out of the loop.

So, now the problem is I don't know how to get that element back. I'm to a point where I can stop at the wanted element and gets stuck there.

Upvotes: 1

Views: 55

Answers (3)

Ken
Ken

Reputation: 548

$.is() returns a boolean, so:

return $(this).is(":visible") ? false: true; is unnecessary.

If you wanted to return the element, form your conditional as follows:

$("ul li").each(function(){
  if($(this).is(":visible")) {
    return $(this);
  } 
});

Using return here will break the loop. It's a common practice when working with loops to abstract the matched results like so:

var matched = [];

$("ul li").each(function(){
  if($(this).is(":visible")) {
    matched.push($(this))
  } 
});

This will add each :visible element to the matched array that will now be available for whatever you need :)

EDIT -

I missed your above line: "If the li indeed is visible then I want the iteration to stop and then get that particular element." Which means that means the answer using $.first() is pretty solid.

Upvotes: 2

elclanrs
elclanrs

Reputation: 94141

You could simply do this:

var $firstVisible = $('ul li:visible').first();

Upvotes: 6

Pointy
Pointy

Reputation: 414036

edit — do what @elclanrs answered for this particular problem; what's below is for when you can't do it with a clever built-in selector trick.


You can have the callback set a variable:

var visibleOne;
$("ul li").each(function(){
  if ($(this).is(':visible')) {
    visibleOne = this; // or $(this) if you prefer
    return false;
  }
});

If you don't like the messy local variable, you could wrap the whole thing up as a jQuery add-on:

$.fn.findVisible = function() {
  var rv;

  this.each(function() {
    if ($(this).is(':visible')) {
      rv = $(this);
      return false;
    }
  });

  return rv;
};

Then:

var visibleOne = $('ul li').findVisible(); // either undefined or a new jQuery object

Upvotes: 2

Related Questions