0

I am trying to change the h1 color after pressing on each color from the options. However, my js code is not working. Any suggestions?

HTML:
<html lang="en">
<body>
    <h1 id="hello">Hello!</h1>
    <select>
      <option value="black">Black</option>
      <option value="red">Red</option>
      <option value="green">Green</option>
      <option value="blue">Blue</option>
    </select>
  </body>
  <script src="test.js"></script>
</html>
JS:
document.querySelector("select").onchange = () => {
  document.querySelector("#hello").style.color = this.value;
};
  • https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable/34361380#34361380 – Teemu Sep 18 '22 at 10:19
  • You cannot infer `this` from an Arrow function. They have no means of *binding*. `this` would be the outer scope pointer, most probably the GlobalThis in your case, not the Element, like you would get it by using a Regular Function `Event function`. Also don't use `on*` listeners unless you're creating a brand new element from in-memory and inserting it to the DOM. Always use `addEventListener()` – Roko C. Buljan Sep 18 '22 at 10:22

1 Answers1

0

In your code this refers to the window but not the select. Use the event object and get the value from the select

document.querySelector("select").onchange = (e) => {
  document.querySelector("#hello").style.color = e.target.value;
};
<h1 id="hello">Hello!</h1>
<select>
  <option value="black">Black</option>
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</select>
brk
  • 48,835
  • 10
  • 56
  • 78