Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Mathematical Function Returning NaN Error (JavaScript)

I am trying to fix a NaN error.

When running the code on the console it gives me the correct answer. However, when I try to print it on a HTML H1 tag the code returns a NaN error.

I tried to use native functions (ie.: parseFloat(), .toString();), but it didn't work as planned.

Could you shed a light, please?

const tempConvert = parseFloat (document.querySelector('input'));

function convertTemp(tempConvert) {
    switch (slt.value) {
        case 'farenheit':
            document.querySelector('h1').innerHTML = `${convertCToF(tempConvert)} Fº`;
            break;
        case 'kelvin':
            document.querySelector('h1').innerHTML = `${convertCToK(tempConvert)} Kº`;
            break;
        default:
            alert('Selec an option.');
            break;
    }
}


function convertCToF(tempC) {
    return tempC * 1.8 + 32;
}

function convertCToK(tempC) {
    return tempC + 273.15;
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have to get input.value, not input. document.querySelector('input') is going to give you the HTML Element of input. If you console.log that, you will see it has a bunch of properties and among them is value, which contains the text inside the input tag.

Also, it's generally a better idea to use innerText than to use innerHTML whenever possible due to security reasons.

const slt = {
  value: 'farenheit'
}

function convertTemp(tempConvert) {
  console.log("Hello");
  switch (slt.value) {
    case 'farenheit':
      document.querySelector('h1').innerText = `${convertCToF(tempConvert)} Fº`;
      break;
    case 'kelvin':
      document.querySelector('h1').innerText = `${convertCToK(tempConvert)} Kº`;
      break;
    default:
      alert('Selec an option.');
      break;
  }
}

document.querySelector("#myBtn").addEventListener('click', () => convertTemp(document.querySelector('input').value));

function convertCToF(tempC) {
  return tempC * 1.8 + 32;
}

function convertCToK(tempC) {
  return tempC + 273.15;
}
<input type='text' />
<button id="myBtn">Convert</button>

<h1>Result Here</h1>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!