1

I'm trying to get the index of an element within an array returned by a jquery selector.

Here's my code:

$("div").click( function(){
  alert( $.inArray( $(this), $("#div") ) );
});

An an example, for this HTML:

<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>

I want it to display "4" when the user clicks the div containing D. Is there any way to do this? This inArray function doesn't seem to do what I expect when applied to selectors.

4 Answers 4

2

You just want:

$("div").click(function(){
  alert($(this).index("div"));
});

(You would need to add 1 to the result of the .index() call since the index is 0-based).

Example: http://jsfiddle.net/andrewwhitaker/tdcVU/

Sign up to request clarification or add additional context in comments.

Comments

0

Another method you could use is the prevAll()

alert($(this).prevAll("div").length + 1);

Comments

0

try

.index()

var selectedItem = $(this); var index = $('div').index(selectedItem);

Comments

0

Here's an update of your code that would work -

$("div").click( function(){
  alert( $.inArray( this, $("div") ) );
});

The changes are -

  • Changed the selector passed into the array argument of inArray from #div to div
  • Passed a normal JavaScript DOM element rather than a jQuery wrapped element into the inArray function

Working demo - http://jsfiddle.net/ipr101/CfY8j/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.