Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda