Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal invocation with document.querySelector [duplicate]

Tags:

javascript

dom

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"
like image 735
Florian Margaine Avatar asked Sep 28 '12 09:09

Florian Margaine


People also ask

What can I use instead of document querySelector?

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.

Does querySelector return a NodeList?

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.

How do I select multiple ids in querySelector?

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.

What is the use of document querySelector () and this template querySelector ()?

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.


1 Answers

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 );
like image 90
Zirak Avatar answered Oct 22 '22 10:10

Zirak