Unable to Change Color of Select Option - javascript

Viewed 13

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;
};
1 Answers

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>

Related