views:

97

answers:

2

Should I be using $("#myElement") or $(myElement)? Both appear to work.

+10  A: 

EDIT: $('#myElement') selects the element in the DOM which has an id of myElement, while $(myElement) expects that the JavaScript identifier myElement be a DOMElement object or a string containing the selector.

Jacob Relkin
My bad, I meant to say $("#myElement") or $(myElement)—which is better or more widely used (both seem to work)?
Tom Marthenal
The former. You need to prefix the element with a `#` or `.` if it is an ID or class respectively.
Russell Dias
To whoever downvoted my answer, the OP's original question had a `#(myElement)` in it, that's what my response was to.
Jacob Relkin
`myElement` can also be a variable containing a jQuery selector string in the case of `$(myElement)`... see my answer.
Peter Ajtai
+1  A: 

You should use the jQuery selectors page as your reference.

There are a lot of selectors to choose from. Try out each one. Here's the two you reference in your question with 2 others:

$("#myElement")    // select and element with the ID "myElement"
$(myElement)       // use the variable myElement as your jQuery selector

$(document)        // The selector can also a DOM OBJECT
                   // document, window ...

$("body")          // To select a DOM element use this form

For example this will hide all the paragraphs on a page. Since the variable myElement is "p", $(myElement) will select all paragraphs on the page into a jQuery object.

var myElement = "p";
$(myElement).hide();

jsFiddle example


This will alert the visible width of the window:

alert($(window).width());

This will alert the contents of the DIV with an ID of myElement

alert($("#myElement").html());

All of this means that $("#myElement") will only select the same thing as $(myElement) if the variable myElement is "#myElement" or functions in an equivalent manner.

Peter Ajtai