Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report

0

  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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!