Hakan Hakan - 13 days ago 7
Javascript Question

Get index/position of element in div - pure javascript

How to get the position of last child in a element, I mean the number (the index)?

I want the code below to alert "4", since there is four elements.

<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<div id="container">
<div id="div1">div1</div>
<div id="div2">div2
<div id="child_div1">div2</div>
<div id="child_div2">div2</div>
</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
</div>
<script>

var container = document.getElementById('container'),
last_child_of_container = container.childNodes.length;

alert('position of last div is'+ last_child_of_container);

</script>
</body>
</html>

Answer

try

document.getElementById('container').children.length

http://jsfiddle.net/pxfunc/MGnCG/

Comments