I need to get the id
of the first closest (nearest) li
parent element when i click on a
element.
<ul>
<li id="wrong1">
<ul>
<li id="p1">
<a href="" class='btn'></a>
</li>
<li id="p2">
<a href="" class='btn'>Click here!</a>
</li>
<li id="p3">
<a href="" class='btn'></a>
</li>
</ul>
</li>
<li id="wrong2"></li>
</ul>
When i clicked on Click here!
, i'm supposed to get li#p2
element.
I used:
$('a.btn').click(function(e) {
var GotIt = $(this).parents().find('li').attr('id');
});
But apparently it didn't work. I also tried closest()
and also the same outcome.
How to get the element properly please?
You should write your script as
$('a.btn').click(function(e) {
var GotIt = $(this).closest('li').attr('id');
});
because "li" is the direct parent of your "a" element, so u can also use like
$('a.btn').click(function(e) {
var GotIt = $(this).parent().attr('id');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With