M.E
M.E

Reputation: 47

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?

Upvotes: 3

Views: 174

Answers (4)

eyelidlessness
eyelidlessness

Reputation: 63529

Neither Javascript nor the DOM define $, which (as other answerers said) is often defined in general-purpose DOM libraries like jQuery, Prototype or Mootools. Based on the particular code you included, I suspect you've been coding against the jQuery API (because you use $.inArray, see http://api.jquery.com/jQuery.inArray/; though your claim that $ aliases document.getElementById confuses matters, as jQuery expects CSS selectors rather than element IDs).

When $ is expected but undefined, that usually means you'll need to include the library whose API you're using in the HTML document.

Upvotes: 0

Tom Gullen
Tom Gullen

Reputation: 61725

$ 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); }

Upvotes: 2

Ben Clayton
Ben Clayton

Reputation: 82219

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?

Upvotes: 4

sushil bharwani
sushil bharwani

Reputation: 30187

$ and document.getElementById is not one of the same thing. $ gives you a function in console only when you are using some library like jquery which mapes $ to a function.

.val id primarly used to get value of the form elements and that is a jquery function. I think you need to learn more around javascript and jQuery

Upvotes: 0

Related Questions