clock menu more-arrow no yes mobile

Filed under:

Easy selector engine with vanilla javascript

If you're like me, you have a hard time remembering all the vanilla javascript DOM selector methods. There's getElementById, getElementsByClassName, and getElementsByTagName as well as the more general querySelector and querySelectorAll. If you come from a jQuery background, these native JS methods might seem overly explicit and hard to remember. Thankfully, the last two methods will let you query just about anything, and they have really great browser support as well.

Next time you need to select a few elements from javascript, but don't want to bother with jQuery or any other standalone selector engines, just pop these two line into the top of your file:

This will allow you to continue using the familiar jQuery-esque selector syntax, with a small (but totally livable) difference. When you use $('.my-class'), it will return a node array with all the objects that match the selector. This is fine when you have multiple instances of .my-class on your page (to access them, you'd just use $('.my-class')[3]), but when you only need to return one unique instance, you can use the second syntax: $_('.one-time-class'). The alternate syntax will return a direct reference to your element without the need to specify an index. You can change the names of the functions to whatever you like, but I find the $ to be easiest to understand. Happy selecting!