简体   繁体   中英

Return ID of a selected element with Javascript

I am writing a simple functionality where I need to get an id of a selected element. My JS is a bit rusty and it's probably pretty obvious but I'm stuck.I'm able to select only the very first time I execute the function but it does not seem to work after the initial selection.

 <ul id="cntyByState" class="dropdown-menu" aria-labelledby="dropState">
       <li id="AZ" class="dropdown-item">Arizona</li>
       <li id="NM" class="dropdown-item">New Mexico</li>
       <li id="TX" class="dropdown-item">Texas</li>
 </ul>

var mst = document.querySelector("#cntyByState li.dropdown-item")

mst.onclick = function(){getCnts(mst)};
   
function getCnts(em) {
        console.log(em.id);
}

What am I missing?

querySelector selects one node only, try querySelectorAll and iterate the node list.

var mst = document.querySelectorAll("#cntyByState li.dropdown-item")

mst.forEach(li => {
    li.onclick = function() {
        getCnts(this);
    };
});
function getCnts(em) {
        console.log(em.id);
}

 function onClickItem() { console.log(this.id); } const dropdownItems = document.querySelectorAll("#dropdown > li"); dropdownItems.forEach((item) => item.addEventListener("click", onClickItem) );
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Static Template</title> </head> <body> <ul class="dropdown" id="dropdown"> <li id="1">mango</li> <li id="2">orange</li> <li id="3">banana</li> </ul> </body> </html>

This is very simple and straight forward example that will easily resolve your problem. I hope this will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM