Get index of specific tags using jQuery

Is there a way to index a specific item with a parent. For instance.

$('h4').click(function(){ alert($('div h4').index('h4')); }); <div> <p>do not include in indexing</p> <p>do not include in indexing</p> <p>do not include in indexing</p> <p>do not include in indexing</p> <h4>Tag I want to include in index</h4> <h4>Tag I want to include in index</h4> </div> 

What I want from this is either a warning 0 or 1, corresponding to the h4 tag that I clicked.

Is this possible with jquery?

Update → → →

Hi guys, thanks for all the answers that most of what you guys suggested, but in working practice this doesn't seem to work. I guess I have problems somewhere else on my page.

thanks anyway

+4
source share
4 answers

try it

 $('h4').click(function(){ alert($('div h4').index(this)); }); 

Sample script: http://jsfiddle.net/L84QV/

+6
source

According to the documentation :

If we use a string as an argument to the .index () method, it is interpreted as a jQuery selector string. The first element among the elements matched with the object, which also matches this selector, is located.


So you can do:

 $('h4').click(function(){ var idx = $(this).index('h4'); alert(idx); });​ 

Demo

+2
source

With this HTML test:

  <div id="main"> <p>do not include in indexing</p> <p>do not include in indexing</p> <p>do not include in indexing</p> <p>do not include in indexing</p> <h4>Tag I want to include in index</h4> <h4>Tag I want to include in index</h4> </div> <div id="test"></div> 

... and this is JS:

 $('h4').click(function() { var index1 = $(this).index("h4"); $("#test").append(index1); });​ 

this adds 0 or 1 to the element of the test div that I added.

jsfiddle: http://jsfiddle.net/8Tfq8/11/

+1
source
 $('>'+this.tagName,this.parentNode).index(this) 

http://jsfiddle.net/doktormolle/ZVmaL/

0
source

Source: https://habr.com/ru/post/1397785/


All Articles