Without explaining the details of the project I'm working on in too much detail, I am trying to determine a way in which I can either implement an event listener for when document.getElementById().value
is accessed, or override it in a similar way to an object, and define custom behaviour for the getting and setting of this value. Is this possible?
I've tried the following, to no avail:
Object.defineProperty(document.getElementById, 'nodeValue', {
get: function () {
console.log('document.getElementById value accessed');
return this.nodeValue;
},
set: function (value) {
console.log('document.getElementById value set');
this.nodeValue = value;
}
});
and the same as above but with value
instead of nodeValue
:
Object.defineProperty(document.getElementById, 'value', {
get: function () {
console.log('document.getElementById value accessed');
return this.value;
},
set: function (value) {
console.log('document.getElementById value set');
this.value = value;
}
});
Apologies if this seems a somewhat farfetched approach, the intricacies of JavaScript behind-the-scenes isn't something I am too familiar with. The above code does show what I am trying to achieve, however. I just don't know how!
I've spent some time on MDN trying to understand just how this works and from what I can gather, getElementById() returns an Element which inherits from the Node interface which contains a nodeValue, and I this that this nodeValue is what I am interested in, but I cannot be certain.
Edit: I'm looking for this behaviour to be generic, I have more than one (but an unknown number of) elements, so I'm not trying to apply this to a specific element.