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

236
Vistas
How to have a function tell whether to apply on "this" or other element ID

I have a function like this:

function toggle(me, style) {
  var myelm = me == '' ? this : document.getElementById(me);
 
  myelm.classList = style; 
}

I want the function to know when it has to apply the style to the triggering element or to some other element like in the following examples:

 <div onclick="toggle(this);"></div> <!--this function should apply to this element only-->
 <div onclick="toggle('otherelement');"></div> <!--this should apply to other element of the DOM-->

but it only works when the ID is specified, and wont apply on this as intended. What is wrong?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In the first case you pass a DOM element, in the second a (non-empty) string. So the condition me == '' that you check is not true in either case. Secondly, this is irrelevant in the function, since you never call it with a this binding (a this binding is not the same thing as passing this as argument).

You'll want to check the data type of the argument, and when it is a string, retrieve the DOM element, and otherwise just use the argument that was given (me) -- not this:

Another thing: you need to call the toggle method on the classList property:

function toggle(me, style) {
  var myelm = typeof me != 'string' ? me : document.getElementById(me);
 
  myelm.classList.toggle(style);
}

NB: make sure to also pass the second argument (style)!

Snippet:

function toggle(me, style) {
  var myelm = typeof me != 'string' ? me : document.getElementById(me);
 
  myelm.classList.toggle(style);
}
.highlight { background: yellow }
<div id="otherelement">This is other element</div>

<p></p>

<div onclick="toggle(this, 'highlight');">toggle this</div>
<div onclick="toggle('otherelement', 'highlight');">toggle other element</div>  
 

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