user3242513 user3242513 - 4 months ago 16
HTML Question

jQuery - get id of a nested single <li> element when right click it

I found a lot of questions about this, but I have problem with getting the single id of a nested

li
element, and I couldn't find answer for it. Here is my code:

$(function() {
$('ul').on('contextmenu', 'li', function(e) {
e.preventDefault();
console.log(this.id);
});


And here is my HTML:

<ul id="u-main-ul">
<li id="1"> 1
<ul id="u-1">
<li id="11">11</li>
</ul>
</li>
</ul>


The problem is that when I right click on the
li
element with
id="11"
, on the console it writes "1 11". When click one
li
element it shows and the id of all others
li
tags that are placed before the clicked one.

I want to get the id only of the right-clicked
li
tag and nothing else.

Answer

You need to stop the event from bubbling up the tree:

$('ul').on('contextmenu', 'li', function(e) {
  e.preventDefault();
  e.stopPropagation();
  
  console.log(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul id="u-main-ul">
  <li id="1">1
    <ul id="u-1">
      <li id="11">11</li>
    </ul>
  </li>
</ul>

See the documentation for more info.

Comments