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

227
Visualizações
How to create shorthand for anyElement.querySelector method

One can create shorthand for document.querySelector with

const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);

so now let a = $('a') and let a = document.querySelector('a') are equivalent.

Is there a way to create shorthand for the querySelector method itself?
I.e. to make let a = element.shortHand(args) and let a = element.querySelector(args) to be equivalent for any (unknown in advance) element.

Edit: Since people are telling that doing the above is a bad idea, there is another question: How to make$ $$ selectors like the one in the Chrome DevTools, which accept the root element as second parameter?
I.e. to make let a = $('a',element) and let a = element.querySelector('a') to be equivalent.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here are some options:

Add Method to Element.prototype

Element.prototype.shortHand = Element.prototype.querySelector

This "monkey-patches" the Element class in the DOM itself and adds this function on all elements in DOM, which is just a copy of the querySelector function.

This is very discouraged. It's bad for performance and it is bad in case browsers decide to add more functions in the future that conflicts with your function. But if you're just playing around and not shipping this code it should be fine.

Mini jQuery

If you're looking to create your own mini jQuery, you can also do something like this:

class MiniJQuery {
  constructor(el) {
    this.el = el;
  }
  shortHand(...query) {
    return this.el.querySelector(...query);
  }
  // ... put any other functions you want to use
}
const $ = (queryOrElement) => {
  if (typeof queryOrElement === 'string') {
    return document.querySelector(queryOrElement);
  }
  return new MiniJQuery(queryOrElement);
}

// Now you can:
const a = $(element).shortHand(args);
// which is equivalent to
const a = element.querySelector(args);

This is a much safer approach and not problematic. I don't think this adds much value as you can just type the slightly longer method name, but you could add more interesting methods on your class to make it worthwhile.

Proxy

Very similar to the approach above, but you can use a Proxy instead of the MinijQuery class to "forward" unknown methods to the element itself. This means that $(element) will have all the methods that element itself has.

Example:


const handler = {
  get: function (target, prop, receiver) {
    if (prop === "shortHand") {
      return target.querySelector.bind(target);
    }
    const retVal = Reflect.get(...arguments);
    
    // Bind methods to the element.
    return typeof retVal === 'function'
      ? retVal.bind(target)
      : retVal;
  },
};

const $ = (queryOrElement) => {
  if (typeof queryOrElement === 'string') {
    return document.querySelector(queryOrElement);
  }
  // You can add all sorts of custom function handlers here.
  return new Proxy(queryOrElement, handler);
}

$('div') // gets divs
$(element).shortHand(...)
// works the same as element.querySelector
// But the HTMLElement methods still work too:
$(element).querySelector
$(element).querySelectorAll
$(element).className
// ...

Read More Here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

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