JQUERY $(element, plainObject)

I ran across this article and a set of interesting jquery syntax:  $(‘<li>’, { text: formatItem(item) }).appendTo($(‘#products’));

So after stumping a few folks and searching the jquery documentation I figured out what exactly it is doing mostly.

This explains the syntax:  http://api.jquery.com/jquery/#jQuery-html-attributes

This explains why its flexibility can lead to unintended consequences…

While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $( “<input>”, {size: “4”} ) calling the .size() method instead of setting the size attribute).

So why not just use attr() to add the attribute text?




$(document).ready(function () {
// Send an AJAX request
.done(function (data) {
// On success, ‘data’ contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$(‘<li>’, { text: formatItem(item) }).appendTo($(‘#products’));

function formatItem(item) {
return item.Name + ‘: $’ + item.Price;