I have an unordered list with li elements in it. When I click on that particular item in the list, I want to extract the value of that li item and use it. In the example below I would want to extract the value "9".
How can I do this in jQuery?
<li sequence="1" title="Category 1" class="liEllipsis selSubCategories" value="9">
<a href="#">
<span class="viewIcons delFaceName _delete fl"></span>
Category 1
</a>
</li>
Firstly, there is no value
attribute available on an li
element, and adding non-standard attributes will mean that your page is invalid. Instead, use data-*
attributes.
You can then hook to the click
event of the a
element and get that data
attribute from its parent li
, like this:
$('li a').click(function(e) {
e.preventDefault();
var value = $(this).closest('li').data('value'); // = 9
console.log(value);
// do something with the value here...
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li data-sequence="1" title="Category 1" class="liEllipsis selSubCategories" data-value="9">
<a href="#">
<span class="viewIcons delFaceName _delete fl"></span> Category 1
</a>
</li>
<li data-sequence="1" title="Category 2" class="liEllipsis selSubCategories" data-value="10">
<a href="#">
<span class="viewIcons delFaceName _delete fl"></span> Category 2
</a>
</li>
</ul>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments