views:

199

answers:

4

This one has me stumped.

<div id="container">
    <div id="store"></div>
    <div id="contact"></div>
</div>

I'm looking for the contact divs position as child of "container". So just to be extra clear, if i'm looking for 'contact's position, i need jquery to return the number 1.

any help is greatly appreciated! thanks!

+1  A: 
var el = document.getElementById("contact");
var i = 0;
while (el.previousSibling != null)
{
   el = el.previousSibling;
   i = i + 1;
}
// i is the index of the item.
David Morton
A: 

Maybe find the parent and iterate through the children until you find the node, counting along the way.

function findPos(id) {
  var child = $('#' + id), children = child.parent().children();
  for (var i = 0; i < children.length; ++i)
    if (children.get(i) == child) return i;
  throw "makes no sense";
}

You could turn that into a jQuery method of course.

Pointy
+2  A: 

You could try something like:

$('#contact').prevAll('div').length + 1

as in get the length of previous div siblings. Omit the +1 if you want a zero-based index.

karim79
you don't need the `+ 1`
nickf
@nickf - you're right, I initially thought he wanted it to start from 1, but I've just re-read the question based on your comment. Anyway, I have edited.
karim79
Works fantastic and didn't have to leave jquery! perfect!
Jeff
A: 

Something like this should work:

var ids = $("#container").children().map(function(n, i) {
    return n.id;
});

var requiredIndex = jQuery.inArray("contact", ids);
Simon Fox