document.querySelector.bind("document")

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?

 

Answer:

This seems to work:

var 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:

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


http://stackoverflow.com/questions/13383886/making-a-short-alias-for-document-queryselectorall
http://stackoverflow.com/questions/14251357/what-is-the-meaning-of-document-queryselector-binddocument
posted on 2015-11-10 16:09 Rhett_Web 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/rhett-web/p/4953370.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值