Reputation: 14641
I have a bunch of nested lists:
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3
<ul>
<li>child-1</li>
<li>child-2
<ul>
<li>grand-child 1</li>
</ul>
</li>
</ul>
</li>
</ul>
With jQuery, with a click or hover, I want to use the item (li). But it gives me it's parent. As in: If I click (or hover) grand-child 1, $(this) returns ITEM-3 (parent's parent)
My jQuery code:
$('ul li').live('click', function(e) {
someVar = $(this).data("dataname"); // (can be .attr(""), etc.);
});
When any of the Li is clicked, how can I use that particular one and not the parent in which it's nested?
Upvotes: 2
Views: 126
Reputation: 79830
I think below is what you are looking for,
$('ul li').live('click', function(e) {
e.stopPropagation();
someVar = $(this).data("dataname");
});
e.stopPropagation();
stop any event propagated to other matching ul li
Note: Please use .on
if you are using jQuery v1.7
as .live
is deprecated.
$(document).on('click', 'ul li', function(e) {
e.stopPropagation();
alert($(this).text()); // (can be .attr(""), etc.);
});
Upvotes: 2
Reputation: 5298
Would this help. if you see console.log, it only return the current clicked item. Read the documentation on stopPropagation here.
"The docs states that stopPropagation Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event."
I also updated live to on, as live has been deprecated as of 1.7
$('ul li').on('click', function(e) {
e.stopPropagation();
console.log($(this));
});
Upvotes: 3