• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

193
Vistas
Método variable para no repetirme: document.getElementById?

Estoy buscando un método en el que pueda crear una variable que contenga document.getElementById e incluir el valor correcto para el ID como valor de variable. Lo que tengo ahora es esto:

 let lenght = parseInt(document.getElementById("lenght").value); let start = parseInt(document.getElementById("start").value); let end = parseInt(document.getElementById("end").value);

Pero lo que me gustaría tener es algo como esto:

 let documentById = parseInt(document.getElementById($elementName).value) let lenght = documentById("lenght"); let start = documentById("start"); let end = documentById("end");

¿Estoy pensando de la manera correcta o es un método que no tiene sentido? Cualquier consejo/sugerencia es bienvenido mientras trato de aprender.

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Puede lograr esto con una función simple que toma la ID del elemento como un parámetro y devuelve el valor según lo previsto

 function documentById(id) { const el = document.getElementById(id); if (!el) return undefined; // element doesn't exist const value = parseInt(el.value, 10); // parsing string to a number (default radix is 10) return isNaN(value) ? { number: false, value: value } : { number: true, value: value }; } const { number, value } = documentById('end'); // if value isnt a number return false (to prevent errors); if (number) console.log(value); // if value is a number log its value else console.log('not a valid number')
almost 3 years ago · Juan Pablo Isaza Denunciar

0

Claro, puedes hacer una función que devuelva solo eso.

 const getValueById = (id) => parseInt(document.getElementById(id).value, 10); const length = getValueById("length"); const start = getValueById("start"); const end = getValueById("end"); console.log({ length, start, end });
 <input id="length" value="5" /> <input id="start" value="2" /> <input id="end" value="6" />

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda