Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
Variable method not to repeat myself for: document.getElementById?

I'm looking for a method where I can make a variable containing the document.getElementById and include the correct value for the ID as a variable value. What I have now is this:

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

But what I would like to have is something like this:

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

Am I thinking in the correct way or is this a method that does not make sense? Any tips/suggestions are welcome as I try to learn.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could accomplish this with a simple function that takes in the ID of the element as a parameter and returns the value as intended

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')
about 4 years ago · Juan Pablo Isaza Relatório

0

Sure, you can make a function that returns just that.

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" />

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda