-2

I'm trying to create a list in HTML where each item in the list can be clicked.But I need to know the ID of the item that was clicked.

I have been trying to have a div surround the list item and have an onClick and a ID tag associated. Then get the ID tag from the synthetic event.

But my list items are complex so they have sub DOM elements. Meaning if I click the <p> it will not return the ID associated with the div tag.

I'm not sure what the best would be to do this? strong text

Aagam Jain
  • 1,546
  • 1
  • 10
  • 18

4 Answers4

0

Here are some solutions you can reference:

  1. If using jQuery, try this api: ele.closest("div") to get the outer div tag
  2. Study the javascript event popup and catch, after that you will get the answer
Jerry
  • 170
  • 8
0

This question got very good answer here: JavaScript - onClick to get the ID of the clicked button

Orginally it demonstrates button click but you can use it for your li element (or any element) that you wish.

Good luck!

A. Meshu
  • 4,053
  • 2
  • 20
  • 34
0

let li = $("li");
li.on("click", getId);

function getId(e) {
   e.stopPropagation();
   let id = $(this).attr("id");
   console.log(id + " was clicked!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li id="element_1">1. Click me</li>
    <li id="element_2">2. Click me
        <ul>
            <li id="element_2.1">2.1. Click me</li>
            <li id="element_2.2">2.2. Click me</li>
            <li id="element_2.3">2.3. Click me</li>
        </ul>
    </li>
    <li id="element_3">3. Click me</li>
    <li id="element_4">4. Click me</li>
</ul>
Swetoslav
  • 28
  • 2
  • 6
0

I hope this helps and if i understood you question correctly in your HTML you can try this

<ul>
  <li><a href="#" id="1" class="test">Coffee</a></li>
  <li><a href="#" id="2" class="test">Tea</a></li>
  <li><a href="#" id="3" class="test">Milk</a></li>
</ul> 

and in jquery try this

 $(document).on("click", ".test", function (e) {
            e.preventDefault();
            alert($(this).attr("id"));
        });
Patrick
  • 1
  • 2