0

The simplified code below does not work but I hope it helps to illuminate the idea I'm testing.

e.target.id returns the name of the id that initiated the function call. In this case it's the id target. Since target is also an object I thought maybe I could reference a key inside the target object. In this case .name. As structured this does not work at all. Do I need to process e.target.id before I use it as a reference? Is this possible at all?

1) I'm aware this might possibly be categorized under worst practices.

2) I'm testing how far I can push JS.

'use strict';

var target = {
  name: 'it worked'
}

document.getElementById('target').addEventListener('click', myFunction);

function myFunction(e) {
  alert(e.target.id.name);  //dies right here
}
<div id="target"></div>
DR01D
  • 1,325
  • 15
  • 32

1 Answers1

2

You could do this with eval or as @Slai mentioned with window[e.target.id].

Be careful with eval: Why is using the JavaScript eval function a bad idea?

var target = {
  name: 'it worked'
}

document.getElementById('target').addEventListener('click', myFunction);

function myFunction(e) {
  //alert(eval(e.target.id).name);  
  alert(window[e.target.id].name);
}
<div id="target">div</div>