user8783104
user8783104

Reputation: 185

Javascript — Why does the getAttribute() function not work on certain attributes?

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>

Upvotes: 0

Views: 193

Answers (2)

user8890700
user8890700

Reputation:

You can't like this?

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

Upvotes: 0

Quentin
Quentin

Reputation: 943571

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.

Upvotes: 4

Related Questions