In the unlikely event that I am
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);
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:
I've done this in the past only to regret it later. Makes your code less portable.
Short answer. I don't recommend it.
not that I know of
Selector = (s,c) => (c ?? document).querySelectorAll(s);
// search in the whole document
Selector('.some, .randomClasses');
// search only in the context of someParent
var someParent = Selector('.give .me .parent')[0];
Selector('img', someParent);
Leverages arrow function expression and Nullish coalescing operator (??) and grouping operator ()
Unless not obvious, this always returns the same stuff, querySelectorAll
would, you can easily adjust this to do similar with querySelector
maybe naming it eg SelectorOne
, you get the picture...
Usage stays the same, but in case someone's worried about it breaking stuff:
if (typeof Selector != "undefined") {
console.warn('CONFLICT WITH Selector! - please address this issue!')
} else {
function Selector(selector, current_context) {
if (typeof current_context == "undefined") {
current_context = document;
}
return current_context.querySelectorAll(selector);
}
}
Select
Selection
which is a different experimental interfaceSelector
, in HTML&CSS world, is specific enough :)
PS: I really do wonder why they made it so long, when that was the main reason people were using heavy libraries (like old jQuery) instead of doing it in plain JavaScript... I really do hope it was a technical reason...
While there isn't any convention, one other solution that I haven't seen mentioned here would be to declare
const querySelector = (sel, el) => (el ?? document).querySelector(sel);
const querySelectorAll = (sel, el) => (el ?? document).querySelectorAll(sel);
which is inspired from @jave.web's answer in syntax.
The advantages are that this is:
document.
in case you're selecting from it;querySelector
will immediately yield results, unlike Selector
. Also, as Steve said, modern IDEs will autocomplete the name anyways so there no need to make it any shorter. Instead of typing doc
"tab" .qu
"tab" you'll be just typing qu
"tab". To me, this seems reasonable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.