Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

javascript - Making a short alias for document.querySelectorAll

I'm going to be running document.querySelectorAll() a whole lot, and would like a shorthand alias for it.

var queryAll = document.querySelectorAll

queryAll('body')
TypeError: Illegal invocation

Doesn't work. Whereas:

document.querySelectorAll('body')

Still does. How can I make the alias work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This seems to work:

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

bind returns a reference to the querySelectorAll function, changing the context of 'this' inside the querySelectorAll method to be the document object.

The bind function is only supported in IE9+ (and all the other browsers) - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind


Update: In fact you could create shortcuts to a whole range of document methods like this:

const query = document.querySelector.bind(document);
const queryAll = document.querySelectorAll.bind(document);
const fromId = document.getElementById.bind(document);
const fromClass = document.getElementsByClassName.bind(document);
const fromTag = document.getElementsByTagName.bind(document);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...