There have been many times we need to find out the position of an element in respect to its siblings.
Here’s a function I‘ve created that returns the position (index) of an element in respect to its siblings.
Here’s a function I‘ve created that returns the position (index) of an element in respect to its siblings.
function GetElementPosition(element) {
return $(element).parent().children().index($(element));
}
Let’s assume we have seven <li> tags, we want to know the position of the element once we click on it.
<ul id="weeklist">
<li>Sunday</li>
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
<li>Thursday</li>
<li>Friday</li>
<li>Saturday</li>
</ul>
jQuery Code:
$(document).ready(function() {
$("#weeklist li").bind('click', function(){
alert( "position: " + GetElementPosition(this));
});
});
Try the demo below, Click on list element to get the position of the element
- Sunday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
Comments
Post a Comment