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

152
Visualizações
return Element if exists using ternary operator by the shorten way as possible in JS

Is there any way to shorten the myFx() function without repeating document.getElementById('myID') ? I just want to return the Element if it exists, if it doesn't, return "false".

The function is working well that manner, but I would like to know if there is any way to shorten it a little more.

HTML:

<div id="myID">Hello World!</div>

JavaScript:

function myFx(){

  return (document.getElementById('myID') === null) ? false : document.getElementById('myID');
  
}

myFx().innerHTML = "Goodbye Cruel World!";
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use Nullish coalescing operator (??).

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

function myFx() {
  return document.getElementById('myID') ?? false;

}

myFx().innerHTML = "Goodbye Cruel World!";
<div id="myID">Hello World!</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

The answer of @c0m1t is correct, just be aware that this might not work in older browsers. I am not sure if it's still a real issue today, but anyway .. here is solution which should work even in ancient browsers.

function myFx(){
  var element = document.getElementById('myID');
  return element || false;
}

myFx().innerHTML = "Goodbye Cruel World!";
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