'Can I make built-in functions return additional properties? [duplicate]
Can I make built-in functions return additional properties?
For example if I call querySelectorAll, can I somehow make the return value contain a desired property (the last element) ?
Instead of:
var elements = document.querySelectorAll('span');
var last = elements[elements.length - 1];
I want to do:
document.querySelectorAll('span').lastElement
Solution 1:[1]
You can, though I wouldn't recommend it - mutating built-in objects is prone to cause problems.
querySelectorAll returns a NodeList, so you can change NodeList.prototype.
Object.defineProperty(
NodeList.prototype,
'lastElement',
{ get: function() {
return this[this.length - 1];
}}
);
console.log(document.querySelectorAll('span').lastElement.textContent);
<span>1</span>
<span>2</span>
A better approach would be to create and use your own function that has the property added to the returned object.
const mySelectorAll = (selector) => {
const list = document.querySelectorAll(selector);
return Object.assign(list, { lastElement: list[list.length - 1] });
};
console.log(mySelectorAll('span').lastElement.textContent);
<span>1</span>
<span>2</span>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
