Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string to $

Tags:

jquery

Trying to get a grip on CoffeeScript and jQuery by doing the Code School CoffeeScript course.

One of the excerpts used is $("<li>" + name + "</li>"). I managed to figure out that $ is an alias for jQuery (right?), so I guess this means we're calling the jQuery function with a string (name is a string, surrounded by two literals).

So... what does the jQuery function do on its own? Tried looking at api.jquery.com, having trouble figuring it out. Thank you!

like image 289
ezuk Avatar asked Jan 29 '26 20:01

ezuk


2 Answers

In this instance you are using jQuery to create a DOM element.

An <li> with some (text I'm assuming) that is in the variable name

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it has somewhere within the string). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements.

The structure for creating DOM elements with jQuery is:

$( html, props )

Check out these jQuery Docs to read more about the jQuery selector.

html: A string defining a single, standalone, HTML element (e.g. or ).

props: A map of attributes, events, and methods to call on the newly-created element.

As we can see in your example we only pass html. $("<li>" + name + "</li>")

like image 143
Mark Pieszak - Trilon.io Avatar answered Feb 01 '26 13:02

Mark Pieszak - Trilon.io


You are actully passing a string to the jQuery "<li>" + name + "</li>" this is actually a concatenate the 3 string to form 1 string. Which is passed to the jQuery function which it parsed and chaeck

if its a string : it is parsed to form a dome selector with complex manuplation to selec element on the basis of id,class,and more complex selector

if its a object : dom related to the object is selected.

if its this (javascript Object) : it is converted to jQuery object

like image 29
GajendraSinghParihar Avatar answered Feb 01 '26 11:02

GajendraSinghParihar



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!