I am not looking for $(this).index()
as an FYI. So, what I have are two <ul>
tags with <li>
tags within them. I want to know which <ul>
was clicked and which <li>
was clicked. For example something like ul 0 and li 3. So if there are 10 <ul>
tags on the page I only want to look at the ones with the list
class for clicks.
jQuery Example that will not work for what I want:
$('ul').click(function(event) { alert($(this).index()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul> <hr /> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul>
The wanted outcome of the clicked element: UL # and LI #. Like UL0 LI3, UL1 LI3, etc...
JSFiddle: http://jsfiddle.net/cg3a8d6n/
You could use click event on li
element and then get its index and also the index of its parent which is ul
. You can also specify selector inside the index
method to consider only specific elements that match the selector.
$('ul.list li').click(function(event) { const li = $(this).index(); const ul = $(this).parent().index('ul.list'); console.log(`ul: ${ul} li: ${li}`) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul> <hr /> <ul></ul> <ul></ul> <ul class="list"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.