Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting Undefined when getting .value from element

Here is the HTML with the bonus life span of 1:

    <h3>PLAYER HEALTH<span value="1" id="bonus-life" >1</span></h3>
    <progress class="playerHealth health" max="100" value="100">100%</progress>

Here is the JavaScript for getting the value of the span and the progress elements:

    const playerHealthBar = document.querySelector(".playerHealth");
    const bonusLifeEl = document.querySelector("#bonus-life");

    console.log("In index.js bonusLifeEl.innerHTML: " + bonusLifeEl.innerHTML);
    console.log(
      "In index.js - bonusLifeEl value & typeof: " +
        bonusLifeEl.value +
        " " +
        typeof bonusLifeEl.value
    );
    console.log(
      "In index.js - player health value & typeof: " +
        playerHealthBar.value +
        " " +
        typeof playerHealthBar.value
    );

I’m able to get the correct playerHealthBar value and typeof, but when I try that with bonus-life all I get is undefined, unless I use innerHTML then I get the "value" in the inner html.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Console log output:

In index.js bonusLifeEl.innerHTML: 1
index.js:8 In index.js - bonusLifeEl value & typeof: undefined undefined
index.js:14 In index.js - player health value & typeof: 100 number

>Solution :

Only input, select, and certain other specific elements have a value property, not span elements. Even though you’ve put a value attribute on your span, that doesn’t get reflected by a value property (it’s also an invalid attribute for span elements). To put an arbitrary value on that element (other than its text content), you’d use a data-* attribute and getAttribute or dataset to retrieve it.

const value = bonusLifeEl.dataset.value;
// Side note: I'd use `getElementById` rather than `querySelector` here
const bonusLifeEl = document.querySelector("#bonus-life");
const value = bonusLifeEl.dataset.value;
console.log(value,);
<h3>PLAYER HEALTH<span data-value="1" id="bonus-life" >1</span></h3>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading