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

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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