0
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 ?

0

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

So how can i understand using "addEventListener" that i which button i click ? I mean, i'm trying to make a dropdown menu using javascript.
At that point, you want to add the event listener right on the parent element, rather than on every single dropdown item.
Can you give me an example about your said thing ?
@MutluŞEN Check my updated answer :D It's there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.