Forum Moderators: open
<ul>
<li onmouseover="thisindex(this);">some text</li>
<li onmouseover="thisindex(this);">some text</li>
<li onmouseover="thisindex(this);">some text</li>
<li onmouseover="thisindex(this);">some text</li>
</ul>
I want thisindex to return the index of the element. For example, the first element would return '0', the second element '1', etc.
I thought I had it with indexOf, but then I remembered that's for finding the position of a character in a string.
The code I've been playing with (doesn't work):
<script>
function thisindex(elm){
var the_li = elm;
var the_ul = elm.parentNode;
var the_index = the_ul.indexOf(the_li);
alert(the_index);
}
</script>
Is there a property that I can access that just knows this information? Otherwise, how can I get the index of the particular element within it's parentNode?
index property for the options themselves. I don't know if it's propreitary or what, but it works in Firefox, too, so it might be safe to use? Especially since the alternative would be to loop through the options list until you find the option that matches the one calling the function.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
</head>
<body>
<script>
function thisindex(elm)
{
var the_li = elm;
var the_ul = elm.parentNode;
var li_list = the_ul.childNodes;var count = 0; // Tracks the index of LI nodes
// Step through all the child nodes of the UL
for( var i = 0; i < li_list.length; i++ )
{
var node = li_list.item(i);
if( node )
{
// Check to see if the node is a LI
if( node.nodeName == "LI" )
{
// Increment the count of LI nodes
count++;
// Check to see if this node is the one passed in
if( the_li == node )
{
// If so, alert the current count
alert(count);
}
}
}
}
}
</script>
<ul>
<li onmouseover="thisindex(this);">some text</li>
<li onmouseover="thisindex(this);">some text</li>
<li onmouseover="thisindex(this);">some text</li>
<li onmouseover="thisindex(this);">some text</li>
</ul>
</body>
</html>
Hope that helps.
Along the same wavelength as Fotiman, I had this:
<script type="text/javascript">
<!--
function thisindex(obj){
//get parent of obj
parentObj=obj.parentNode
//get all li elements of parentObj
litems=parentObj.getElementsByTagName('li')
//cycle through litems to find obj
for (i=0;i<litems.length;i++){
if (litems.item(i)==obj){
alert(i)
}
}
}
//-->
</script>
</head>
<body>
<ul id="myUL">
<li id='li1' onmouseover="thisindex(this);">some text</li>
<li id='li2' onmouseover="thisindex(this);">some text</li>
<li id='li3' onmouseover="thisindex(this);">some text</li>
<li id='li4' onmouseover="thisindex(this);">some text</li>
</ul>
</body>
ajkimoto
function thisindex(elm)
{
var nodes = elm.parentNode.childNodes, node;
var i = count = 0;
while( (node=nodes.item(i++)) && node!=elm )
if( node.nodeType==1 ) count++;
alert(count);
}