Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda