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

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

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 Denunciar

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