Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add an action listener for a <li> tag using its id?

I am creating a li tag that once the user clicks it, it will post something on the console using javascript.

Here is my index.html:

$('#Title').on('click', function(){
  console.log("List was clicked.");  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="Title"> List 1 </li>
<li id="Title"> List 2 </li>
<li id="Title"> List 3 </li>

But it doesn’t do anything, are there any approach to this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue is because you are using the same id attribute for each item in the list. It has to be unique in the document. You can use a class if you want to give the same name. See Example below:

HTML:

<li class="Title">List 1</li>
<li class="Title">List 2</li>
<li class="Title">List 3</li>

JS:

$('.Title').on('click', function(){
    console.log("List was clicked.");
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading