Mike Eng
Mike Eng

Reputation: 1681

jQuery how to search for an element at a given index or later

I have html of basically

<div class="letter">A</div>
<div class="letter">B</div>
<div class="letter"></div>
<div class="letter">D</div>
<div class="letter"></div>

and a jQuery function that is returning the index of the first empty div (with the class "letter")

var firstEmptyIndex;

var findStart = function(){
    var firstEmptyElement = $('div.letter:empty:eq(0)');
    firstEmptyIndex = firstEmptyElement.index('div.letter');
}

How can I extend this findStart function to pass a variable that will begin searching for an empty element at a given index. For exmaple, I want to run findStart(3), which would return the index of the fifth element in the HTML example (4). Running findStart(0) or findStart(1) would return 2.

Upvotes: 1

Views: 91

Answers (5)

bfavaretto
bfavaretto

Reputation: 71939

You can use a combination of :gt and :first:

var findStart = function(i){
    return $('div.letter:gt(' + i + '):empty:first').index('div.letter');
}

Upvotes: 3

Hemen Ashodia
Hemen Ashodia

Reputation: 202

Try this one it will work
it returns null is no empty elements are found.
other wise it will return next empty element index

var findStart = function(n){
    var i=n-1,l=$('div.letter').length;
    for(;i<l;i++){
        if($('div.letter').eq(i).html()==""){
            return i;
        } 
    }
    return null;
}

Upvotes: 0

ColBeseder
ColBeseder

Reputation: 3669

Use the jQuery's filter method to return just the elements without text.

var selector = ".letter" ;
$(selector).filter(function(){return !$(this).text()}).get(0) ;

Upvotes: 0

epascarello
epascarello

Reputation: 207537

slice(start[,end]) method or :gt(index) selector

Upvotes: 0

Rafe Kettler
Rafe Kettler

Reputation: 76965

You can make use of JQuery's filter method, which, in one form, allows you to pass a filtering function that takes in your index. So, the following should work:

someResultSet.filter(function (i) { return i < someOtherIndex; })

Upvotes: 0

Related Questions