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!
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.
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)