DEV Community

Discussion on: Who still regularly uses jQuery?

Collapse
 
pavelloz profile image
Paweł Kowalski • Edited

This is how my utility looks like for that:

const $ = (s, p = document) => {
  if(/object HTML.*Element/.test(s.toString())) {
    throw new Error('[utils/dom/$] Passed dom element instead of selector (string).');
  }

  return Array.from(p.querySelectorAll(s))
};

export default $;

I even export it as $ because i got so used to it ;-)))

I should note that it always returns an array, so no matter if it returns one element or multiple, you can still have one code to iterate matching elements. And if you need only one because you know there will be only one, [0] saves the day, just like in jquery unwrapping method.

Collapse
 
maxxheth profile image
Maximillian Heth

That's pretty nifty!

I made a slight adjustment that will save you the trouble of having to add [0] to the array if there's really only one instance of that selector.


const $ = (selector, context = document) => {

  if(/object HTML.*Element/.test(selector.toString())) {

    throw new Error('[utils/dom/$] Passed dom element instead of selector (string).');

  }

  if (context.querySelectorAll(selector).length > 0) {

    return [...context.querySelectorAll(selector)];

  } else {

    return context.querySelector(selector);

  }

};

Thread Thread
 
pavelloz profile image
Paweł Kowalski

I had it in previous version, but i value having returned array much more than this. Because i often map, i can safely map over array of one element, but it would throw if i dont have it inside the array. Im huge advocate of that.