Possible Duplicate:
JavaScript function aliasing doesn't seem to work
Related jsfiddle: http://jsfiddle.net/cWCZs/1/
The following code works perfectly:
var qs = function( s ) {
return document.querySelector( s );
};
qs( 'some selector' );
But the following doesn't:
var qs = document.querySelector;
qs( 'some selector' ); // Uncaught TypeError: Illegal invocation
I don't understand why.
My confusion comes with the fact that this works:
function t() {
console.log( 'hi' );
}
var s = t;
s(); // "hi"
The other alternative is element. query / queryAll . These are alternative methods to querySelector and querySelectorAll that exist on DOM parent nodes. They also take selectors, except these selectors are interpreted relative to the element being queried from.
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements. Here is the HTML for the examples in this article.
Document.querySelector() The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
The problem lies in the this
value.
//in the following simile, obj is the document, and test is querySelector
var obj = {
test : function () {
console.log( this );
}
};
obj.test(); //logs obj
var t = obj.test;
t(); //logs the global object
querySelector
is not a generic method, it will not accept another this
value. So, if you want a shortcut, you must make sure your querySelector
is bound to the document:
var qs = document.querySelector.bind( document );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With