Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda