Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!