'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 ?
Solution 1:[1]
Two issues:
document.querySelectoronly selects one element - the first element that matches the specified selector. You should usedocument.querySelectorAllto grab an array of elements..classnameshould 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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
