Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A few questions about JavaScript basics - $, "is not a function"

Being fully self-taught without actually reading up on JavaScript (It's my job now, believe it or not) there are a few things I accept but don't understand.

The first one is the dollar sign.

As far as I use understand it, it's a shortcut to document.getElementById(), but if I log $ and document.getElementById() to console - Only $ returns a value. This value however is always function(), shouldn't it be. The element? What gives?

The second issue I have is something that keeps coming up in my code and I go out of my way to change the code to eliminate it. It's the "... is not a function" error.

For example:

if ($.inArray($(div_id).val(), arr) >= 0);

Will give the error .val() is not a function. Why? And how do I use the value of div_id to see if it's in array?

like image 617
M.E Avatar asked Apr 18 '26 11:04

M.E


2 Answers

Hiya. When you're using Jquery (which I assume you are), then $ will return the jquery object. This can contain an array of matched HTML elements depending on the selector you used. For example $("#foo") will return the jquery object containing the element with id foo. You can get the actual HTML DOM element out using $("#foo")[0] - using the array-style notation.

Can you give us some more info on what you're trying to achieve with the $.inArray example?

like image 166
Ben Clayton Avatar answered Apr 20 '26 00:04

Ben Clayton


$ is a valid variable name.

So if you try to use $ without setting it, it will not work.

A lot of people/frameworks however use $ as a shortcut to document.getElementById, they would declare it at the top of the script as:

function $(id) { return document.getElementById(id); }
like image 27
Tom Gullen Avatar answered Apr 19 '26 23:04

Tom Gullen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!