------HTML code--------
<div>
<p id="selectText">All Categories</p>
<ul>
<li >A</li>
<li >B</li>
<li >C</li>
<li >D</li>
</ul>
</div>
------JS code-------------
const options = document.getElementsByClassName("options");
const selectText = document.getElementById("selectText");
for (option of options) {
option.onclick = () => {
selectText.innerHTML = this.innerHTML;
}
}
I tried to change my dropdown menu name "All categories" to the menu item I clicked (A, B, ...)
But all I got was undefined :(
I guessed there's something wrong with "this.innerHTML" But I just couldn't solved it
HELPPPP :(((
CodePudding user response:
Change your JS code to this:
for (let option of options) {
option.onclick = () => {
selectText.innerHTML = option.innerHTML;
}
}
You just need to get the innerHTML of the individual option, no need for the this
.
Demo: https://stackblitz.com/edit/js-qvyyef?file=index.js,index.html
CodePudding user response:
First off, optionsEl is not defined, you need to loop through the options array instead. The following works with a forEach loop:
const options = document.querySelectorAll(".options");
const selectText = document.getElementById("selectText");
options.forEach((option) => {
option.onclick = () => {
selectText.innerHTML = option.innerHTML;
}
})
<div>
<p id="selectText">All Categories</p>
<ul>
<li >A</li>
<li >B</li>
<li >C</li>
<li >D</li>
</ul>
</div>