I trying to return that text inside of the list but instead Im getting htmlcollection0
my JS:
Array.from(document.getElementById("main-menu").getElementsByTagName("li")).forEach(
(x) =>
(x.onclick = () =>
console.log({
event_name: "menu item clicked",
menu_item: x.getElementsByTagName("li"),
}))
);
my html:
<div id="main-body">
<ol id="main-menu">
<li class="selected">Shop Spirits</li>
<li>Shop Bourbon</li>
<li>Shop Scotch</li>
<li>Shop Rum</li>
</ol>
x.getElementsByTagName('li')
returns all the li
elements nested inside x
. There aren't any, so that returns an empty NodeList.
If you want to log the text of the clicked item, use x.innerText
, there's no need to search for anything.
Array.from(document.getElementById("main-menu").getElementsByTagName("li")).forEach( (x) => (x.onclick = () => console.log({ event_name: "menu item clicked", menu_item: x.innerText })) );
<div id="main-body"> <ol id="main-menu"> <li class="selected">Shop Spirits</li> <li>Shop Bourbon</li> <li>Shop Scotch</li> <li>Shop Rum</li> </ol>
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.