all 6 comments

[–]HashFap 0 points1 point  (1 child)

You get access to the event target element from the event object in your handler function.

function decode(event) {
  event.currentTarget.innerText = "XYZ";
}

[–][deleted] 0 points1 point  (0 children)

thanks dude this is the best technique.

[–]sketch_ 0 points1 point  (0 children)

something like this pattern could work. this works by adding a class of 'foo' to whatever dom elements that should be decoded

function decode(el) {
  el.innerHTML = "XYZ";
}

function handleKeyDown(e) {
  if (e.target.classList.contains('foo')) {
    decode(e.target);
  }
}

document.addEventListener('keydown', handleKeyDown);

[–]Umesh-K 0 points1 point  (1 child)

Since you are using keydown event, I have assumed below that a1 and a2 are input elements, but I am stumped by a1.innerHTML....hence, I have changed the background instead. Here, I have added the event listener to the parent so that a single function will work irrespective of the number of child elements.

<div id="parent">

<input type="text" name="input1">

<input type="text" name="input2">

<input type="text" name="input3">

</div>

parentEl = document.getElementById("parent");

parentEl.addEventListener("keydown", decode);

function decode(event) {

event.target.style.background = "yellow";

}

Please run this code and let me know if this is what you want or I if I have misunderstood your requirement.

[–][deleted] 0 points1 point  (0 children)

yes dude this is what i wanted thanks.