How to get indexing of an element using javascript

I have an element in the body. I want to know their indexing, how the indexing of a div should be 1 and its indexing should be 2. How to start a search

$(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>
+5
source share
2 answers

You can do this very easily in jQuery (I see that you are using it) 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/

+2
source

Try as below, this will help you ...

Fiddle: http://jsfiddle.net/RYh7U/136/

HTML:

<body>
<div></div>
<span></span>
<p></p>
<strong></strong>
</body>

Javascript:

$(function(){
var id= document.body.getElementsByTagName("*");;
for(i=0; i<id.length;i++){
    alert(" Tagname : " + id[i].tagName + "  Index : " + i)
}})
+1
source

All Articles