0

Why does the alert display the correct value (which is pl) when i use alert(el2.getAttribute("class"));but does not do so when I use alert(el2.getAttribute("value")); (which is supposed to be the value for each option such as sunny... etc).

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Allowance updater example</title>
      </head>
      <body>

      <label for="weather">Select the weather type today: </label>
<select id="weather">
  <option value="" class = "pl">--Make a choice--</option>
  <option value="sunny" class = "pl">Sunny</option>
  <option value="rainy" class = "pl">Rainy</option>
  <option value="snowing" class = "pl">Snowing</option>
  <option value="overcast" class = "pl">Overcast</option>
</select>

<p></p>
      <script>
          var el = document.querySelector("select");
          var el2 = document.querySelector("option");
          el.addEventListener("click", x);
          function x() {  
          alert(el2.getAttribute("value"));
        alert(el2.getAttribute("class"));
          }
      </script>
        </body>
</html>
1
  • 1
    Why not use the value property? el.value? Commented Nov 6, 2017 at 16:56

2 Answers 2

4

which is supposed to be the value for each option such as sunny... etc

No. It is supposed to be the value attribute for the particular element that is stored in e2.

var el2 = document.querySelector("option");

… and that is the first option element in the document.

<option value="" class = "pl">

… which is an empty string.

If you want to get all the options then you need to get them all (querySelectorAll) and then loop over the resulting list of elements as if it were an array.

Sign up to request clarification or add additional context in comments.

2 Comments

ok thank you, but what if I call the event listener on el2 (option instead) like this el2.addEventListener("click", x); Why doesn't this work (displays nothing in this case)?
IIRC option elements can't have click events bound to them because of the way their are implemented (also that would still target only the first option element)
0

You can't like this?

<script>
      var el = document.querySelector("select");
      el.addEventListener("change", x);
      function x() {  
        alert(el.value);
      }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.