HTML element's value property is giving undefined value

三世轮回 提交于 2021-02-05 12:09:26

问题


This is totally mysterious. I checked everything, googled everything, but looks like this should work. I've done same things in my code with others html elements and they all give me the values, but this time I'm getting undefined for this particular HTML element. The snippet of code below:

<div class="pianoKeyboard">
    <button id="octaveUp" value="off">Octave Up</button>
    <button id="octaveDown" value="off">Octave Down</button>
    <div id="octaveNum" value='0'>Default</div>

var octaveNumber = document.getElementById("octaveNum");

    octaveup.addEventListener("click", function(e) {
      if (booleanVal == false) {
        booleanVal = true;
        console.log(octaveNumber.value);

Do you see any problem? Because I don't. I can console.log the element itself without the value, but if I add .value to it, I get undefined.


回答1:


That is because <div> elements do not have a value attribute. It is only for a selected subset of elements: <button>, <option>, <input>, <li>, <meter>, <progress>, and <param>.

You can store the value as a HTML5 data- attribute, i.e.:

<div id="octaveNum" data-value='0'>Default</div>

The value of the data- attribute can simply be accessed programmatically using:

document.getElementById('octaveNum').dataset.value

The data- attribute offers you tremendous flexibility over the naming of variables: it doesn't even have to be data-value. For example, if you want to store the default and current octaves, you can choose to store it as data-default-octave and data-current-octave, and access it as selector.dataset.defaultOctave and selector.dataset.currentOctave respectively (note the conversion of dash-delimited attribute name in HTML5 to camelCase keys in JS).

Data attribute names which contain hyphens will be stripped of their hyphens and converted to CamelCase.

See proof-of-concept below:

var octaveNumber = document.getElementById("octaveNum");
var octaveUp = document.getElementById("octaveUp");
octaveUp.addEventListener("click", function(e) {
  console.log(octaveNumber.dataset.value);
});
<div class="pianoKeyboard">
  <button id="octaveUp" value="off">Octave Up</button>
  <button id="octaveDown" value="off">Octave Down</button>
  <div id="octaveNum" data-value='0'>Default</div>
</div>



回答2:


div element have no value attribute, so you can't use octaveNumber.value to get it



来源:https://stackoverflow.com/questions/45664269/html-elements-value-property-is-giving-undefined-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!