Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of specific tags using Jquery

Tags:

jquery

Is there a way to only index a specific element with in a parent? For example:

$('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 an alert of 0 or 1 corresponding to the h4 tag I have clicked.

Is this possible with jquery?

Update

Thanks for all the answers, what most of what you guys have offered works, but in working practice it doesn't seem to function. I guess I have issues somewhere else in my page.

Thanks Anyway

like image 580
Psylant Avatar asked Jan 17 '23 10:01

Psylant


2 Answers

try this

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

fiddle example : http://jsfiddle.net/L84QV/

like image 143
dku.rajkumar Avatar answered Jan 31 '23 09:01

dku.rajkumar


According to documentation:

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


So you could do:

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

DEMO

like image 39
Didier Ghys Avatar answered Jan 31 '23 07:01

Didier Ghys