There have been a number of times recently where I've needed to know what position a DOM element lies in relation to it's siblings. Let's try that again in English: imagine we have five sibling (i.e. they share the same parent element) <div> tags on a page and the user clicks one of them; I want to know if they clicked the first one, or the second one, or third etc.
Luckily, I found it to be dead easy. Here is my little function which tells us just that:
function GetSiblingNumber(oElement) {
return $(oElement).parent().children(oElement.nodeName).index(oElement);
}And here is an example for good measure:
$(document).ready(function() {
$("li").click(function() {
alert("This is element #" + GetSiblingNumber(this));
});
};Try the above by clicking on the list elements below (as always, position IDs are zero-indexed, i.e. numbering starts from 0, not 1):
Useful stuff:
Code Snippets:
Recommended reading: