JQuery: Given only the element id name, how does it find its position in dom relative to its parent?

I have me at a standstill.

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

I am looking for the position of the contacts div as a child of the "container". Therefore, to be more clear, if I am looking for a "contact position", I need jquery to return the number 1.

any help is much appreciated! thanks!

+3
source share
4 answers

You can try something like:

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

as well as for getting the length of the previous siblings. Omit +1 if you need a zero-based index.

+2
source
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. 
0
source

, , node, .

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";
}

, jQuery.

0

- :

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

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

Source: https://habr.com/ru/post/1720412/


All Articles