Ben
Ben

Reputation: 10288

Why does this work in jQuery?

I'm trying to understand why something works the way it does in jQuery. When I want to apply a jQuery extension, for example datatables, I run the command:

$("#some_id").datatables(.. parameters ..);

I don't know why this works, obviously the DOM element didn't have a method datatables() beforehand.

Thanks!

Upvotes: 2

Views: 88

Answers (4)

Tadeck
Tadeck

Reputation: 137320

The reason for that is because you are not making this call on DOM element - you are making it on jQuery object that stores the information on the DOM objects it should influence.

And the reason .datatables() is available is that some plugin (probably DataTables) made it accessible in the way similar to this:

jQuery.fn.my_foo_func = function(){
    console.log(jQuery(this));
};

If you apply the above, you will be able to do something like that:

$("#some_id").my_foo_func();

which will pass to the console the jQuery object(s) on which you invoked it.

Is it clear enough?

Upvotes: 4

Andrew Stubbs
Andrew Stubbs

Reputation: 4462

$("#some_id") does not return a HTML DOM element, it returns a JQuery object wrapping it.

This JQuery object does have the datatables method.

Upvotes: 5

Morgan Delaney
Morgan Delaney

Reputation: 2439

You installed a plugin which added a method, .datatables(), to the jQuery() object, often abbreviated as $(). If you're interested in creating your own jQuery() object methods, here's a Google search to get you started.

Upvotes: 0

Mart
Mart

Reputation: 5788

Once you call $("#some_id") you no longer have a DOM object but a jQuery object. The DOM object is reachable with $("#some_id")[0].

Upvotes: 0

Related Questions