2

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
amani
  • 23
  • 2

1 Answers1

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you. I'll go with the second "better" approach. Is it more prone to errors if I don't use object.assign? E.g.: function myfunc(selector) { var elements = document.querySelectorAll(selector); elements.lastElement = elements[elements.length - 1]; return elements; } – amani Apr 06 '22 at 16:55
  • @amani the 1st approach is a more direct answer to your question. – Ergis Apr 06 '22 at 16:58