Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
Can I make built-in functions return additional properties?

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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!