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

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

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 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