1

Say,I have 5 paragraphs in the page.

if I execute:

p_array=$('p');
second_p=$('p:eq(1)');
$.inArray(second_p,p_array);

I get -1. Any explanation?

2
  • second_p is a jQuery object, and p_array is an array-like object which contains DOM nodes... Therefore, p_array obviously does not contain second_p. Commented Jun 13, 2011 at 0:36
  • Why not second_p = p_array.eq(1);? You're doing two look-ups unnecessarily. Commented Jun 13, 2011 at 0:38

2 Answers 2

4

Neither p_array nor second_p are arrays.

They are jQuery objects.

More specifically, p_array is a jQuery object containing a set of 5 DOM nodes. second_p is a jQuery object containing a set of 1 DOM node.

$.inArray can function on these jQuery sets of nodes, but you can't compare a set against a set.

If you extract that one DOM node using the array subscript operator (jQueryObj[i]), then you're no longer comparing a set against a set:

var p_array=$('p');
var second_p=$('p:eq(1)');
alert($.inArray(second_p[0], p_array)); // result: 1

See a live demo here.

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

1 Comment

@xiaohan2012: Yea, we like it :)
1

Both p_array and second_p are array-like jQuery objects. You want to extract the actual DOM node for the <p> and test it like:

$.inArray(second_p[0], p_array);

That call returns 1 for me, as expected.

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.