tags:

views:

54

answers:

3

From the context of the code I am reading, it seems like $("<tag></tag>") creates a tag, where as $('<tag>') is a selector that searches for a tag. What's going on here? Actually I might not have the syntax of the second one right, but I'm sure I've done $('idName') like this before.

What's going on?

+2  A: 

Create an element:

$("<div>Hello</div>").appendTo("body"); // <body><div>Hello</div></body>

Select the DIVs:

$("div").addClass("myClass"); // <div></div> -> <div class='myClass'></div>

Select an element by its ID:

$("#myDiv"); // selects <div id='myDiv'>Hello World</div>

And by its class:

$(".myDiv"); // selects <div class='myDiv'>Hello World</div>
Jonathan Sampson
A: 

There's no difference between double quote and single quote.

Jonathan gave you a good example of the different between selector and and DOM element creation. It can be done with this too:

Create an element:

$('<div></div>');
$("<div class='class1'></div>");
$('<div attrib="val"></div>');

Select the DIVs

$('div');

However $('<tag>') DOES NOT select a tag. Refer to the docs.

o.k.w
+1  A: 

The difference between $("<tag></tag>") and $("<tag>") and $("<tag />") is personal style/preference (unless you're using IE, apparently. see comment). All three will use the native createElement() method to create a now DOM element. If the tags have parameters it will parse them create the element by some other means.

More info on creating things here: http://api.jquery.com/jQuery/#jQuery2

To select elements by id, you'd use $("#idName").

To select existing elements by tag name, $("tag").

To select existing elements by class name, $(".className").

More info on selecting things here: http://api.jquery.com/jQuery/#jQuery1

Ryan Graham
Ryan, the difference is not just personal preference but can actually cause problems in IE if you use $("<tag>"). At least according to core jQuery team member Cody Lindley in his book jQuery Enlightenment.
Doug Neiner
Thanks for the pointer. One more reason to be glad I can generally ignore IE on internal apps.
Ryan Graham