开发者

jQuery: Given just an element ID name, how do it find its position in the dom relative to its parent?

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!


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.


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. 


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.


Something like this should work:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜