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

133
Views
How can i get classname of element of foreach in Javascript?
const dropdownmenu = document.querySelector(".dropdownmenu")

dropdownmenu.forEach(element => {
    
    console.log(element.classname)
    
});

Question is How can i get classname of element of foreach in Javascript ?

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

0

Two issues:

  1. document.querySelector only selects one element - the first element that matches the specified selector. You should use document.querySelectorAll to grab an array of elements.
  2. .classname should be camelcased -> .className

I'm assuming you are trying to grab the elements inside of the dropdown menu. Here's how you'd do that:

<ul class="dropdown-menu">
    <li class="item">item1</li>
    <li class="item">item2</li>
    <li class="item">item3</li>
</ul>

<script>
    const menu = document.querySelector('.dropdown-menu')

    for (const elem of menu.querySelectorAll('.item')) {
        console.log(elem.className);
    }
</script>

If you're trying to listen for events on the dropdown menu for all of the items, try putting the event listener right on the parent and using e.target to target the clicked child.

<p>Click the items</p>
<ul class="dropdown-menu">
    <li class="item">item1</li>
    <li class="item">item2</li>
    <li class="item">item3</li>
</ul>

<script>
    const menu = document.querySelector('.dropdown-menu');

    menu.addEventListener('click', (e) => {
        console.log(e.target.textContent);
    });
</script>

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!