JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Replace MouseEvent.target</h1>
<div>Curious, can you replace e.target without cloning to a new object?</div>
<ol>
<li id="one">Unmodified target (should be LI)</li>
<li id="two">Overwrite target (P wanted, but should be LI)</li>
<li id="three">Plug target on instance 1 (P wanted, but should be LI)</li>
<li id="four">Plug target on instance 2 (P wanted, but should be undefined)</li>
</ol>
<hr>
<div id="log"><!-- log messages here --></div>
JavaScript
var one = document.querySelector('#one');
var two = document.querySelector('#two');
var three = document.querySelector('#three');
var four = document.querySelector('#four');
var log = document.querySelector('#log');
function logTarget (e) {
log.innerHTML += 'e.target.nodeName === "' + (e.target ? e.target.nodeName : 'target is undefined') + '"<br>';
}
one.addEventListener('click', function(e) {
// default behaviour, don't modify the event at all
logTarget(e);
});
two.addEventListener('click', function(e) {
// replace the value on the same object, which seems to be read-only
e.target = document.createElement('p');
logTarget(e);
});
three.addEventListener('click', function(e) {
function F(target) {
// set another property of the same name on an instance object
// which sits in front of our event
this.target = target;
}
// put the original object behind it on the prototype
F.prototype = e;
logTarget(new F(document.createElement('p')));
});
four.addEventListener('click', function(e) {
// create a new object with the event behind it on the prototype and
// our new value on the instance
logTarget(Object.create(e, {
target: {
value: document.createElement('p')
}
}));
});