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

159
Vistas
How can i take value from event onClick in variable?

How can i take value from event onClick in variable?

I have button with two span with languages in my html

<button class="switch" >
<span class='span switch_span spanlg span-dark' id = 'en' data-lang="en">EN </span>
<span class='switch_span1 spanlg'>/</span> 
<span class='span spanlg span-dark' id = 'ru' data-lang="ru" >RU</span>
</button>

and i need to receive in variable onclick id or data-lang in script.js

i try below, but it doesn't work

const span = document.querySelectorAll('.span');

var postId='';

span.forEach(function(spa) {

    spa.addEventListener('click', function() {
      postId = this.getAttribute('id');
      return postId;
    })
})

console.log(postId)

and postId didn't receive id

i need to have this id in variable

Thank you very much for your help!

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

0

You should get the target from a parameter of your listener function, like:

function(event) {
  postId = event.target.id;
}

Chek this for more information: https://developer.mozilla.org/en-US/docs/Web/API/Event/target

Also note that the variable is set only after the event is triggered.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You just aren't calling console.log at the right time or in the right place

span.forEach(function(spa) {

    spa.addEventListener('click', function() {
      postId = this.getAttribute('id');
      console.log("id: " + postId);
      return postId;
    })
})

//console.log(postId)
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