Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element indexing using javascript

I have some element in body. I want to know their indexing like div indexing should be 1 and span its indexing should be 2. How to start find

$(function(){
var id= document.getElementsByTagName('*');
for(i=0; i<id.length;i++){
alert(id[i])
}})

<body>
<div></div>
<span></span>
<p></p>
<strong></strong>
</body>
like image 707
Jitender Avatar asked Oct 21 '22 12:10

Jitender


1 Answers

You can do this very easily in jQuery (I can see you're using it), by using this code:

$(function(){
   $.each($('body *'), function(i, v) { // All elements within the <body> tag
      var index = (i + 1); // zero-based index, so plus 1.
      console.log(index);
   });
})

jsFiddle example here: http://jsfiddle.net/u7kWF/

Pure JS example:

var id = document.body.getElementsByTagName('*'); // Get all tags within <body>
for(i=0; i<id.length;i++){
     console.log(id[i]); // The tag - <div>, <span>, <p>, <strong>
     console.log(i + 1); // The index - 1,2,3,4
}

jsFiddle: http://jsfiddle.net/u7kWF/1/

like image 54
Chris Dixon Avatar answered Oct 24 '22 02:10

Chris Dixon