Norse
Norse

Reputation: 5757

JQuery get current array index position

I have an array and a div:

var urls = ["google", "yahoo", "facebook"];

<div class="yahoo"></div>

Is it possible to get the array index of whichever element is loaded as the div's class?

I have tried:

alert(urls.index());

and my page breaks.

Upvotes: 1

Views: 14231

Answers (2)

adeneo
adeneo

Reputation: 318242

var urls = ["google", "yahoo", "facebook"];

var pos = getPosition(urls, 'yahoo'); //returns 1

function getPosition(arrayName,arrayItem) {
    for(var i=0;i<arrayName.length;i++){ 
        if(arrayName[i]==arrayItem)
        return i;
    }
}​

FIDDLE

Upvotes: 1

Ram
Ram

Reputation: 144689

You can try $.inArray utility function.

var urls = ["google", "yahoo", "facebook"];    
var cls = $('div').attr('class');
var ind = $.inArray(cls, urls);

Upvotes: 8

Related Questions