Search code examples
javascriptconventions

Is there a convention for renaming document.querySelector etc in JavaScript?


In the unlikely event that I am

  1. writing JavaScript
  2. don't want to use a framework like jQuery
  3. want to replace frequent calls to 'document.querySelector' with something shorter
  4. want my code to still be readable and familiar to new developers who look at it

Are there any abbreviations that are commonly used to replace querySelector, querySelectorAll, etc?

This is a question about naming conventions. I'm not asking how to abbreviate a long function name. For reference, you can do it like this:

var queryAll = document.querySelectorAll.bind(document);

Solution

  • No, there isn't.

    Furthermore, I don't think its a good idea to use abbreviations. Why change the Javascript API for no other reason than to make it shorter?

    You could reuse something like $, but then you might give the reader the impression that you are using an existing library that uses that abbreviation.

    Some other considerations:

    • What happens if you later decide to add a library that uses the same abbreviation? You need to refactor your code
    • What happens if someone wants to reuse some of your code and your abbreviations conflict with there code or libraries.
    • With modern editors / IDEs, using abbreviations will not likely reduce the amount of typing if you are using auto fill
    • For someone learning Javascript it will most likely make make your source confusing to read.

    I've done this in the past only to regret it later. Makes your code less portable.

    Short answer. I don't recommend it.