7

I'm new to JQuery and trying to use it to dynamically build HTML based on results of a query for JSON objects. Anyways on the JQuery API site (http://api.jquery.com/jQuery.getJSON/) I found this example where I don't understand the syntax and I can't seem to find any explanation of why this syntax is legal or how to use it.

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  // *** THIS IS THE PART THAT IS WEIRD ***
  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

Can someone refer me to documentation that explains the syntax with the comment above it?

3
  • Ok thanks all, now I get it after all the responses. For some reason the only context for '$' that I ever noticed was it being a selector. Commented Jan 6, 2012 at 18:10
  • Worth noting: There are many ways to add multiple elements to the DOM. This approach is usually the most efficient, because you're building an array in memory and adding it all to the DOM at once at the end. Commented Jan 6, 2012 at 18:32
  • @midnitex31 - Please be sure to select one of the answers as "the answer." Just click the check mark next to the answer that helped you the most. Thanks! Commented Jan 6, 2012 at 18:52

7 Answers 7

4
$('<ul/>')

Creates a new UL element not attached to the DOM

$('<ul/>', {'class':'my-new-list'})

Sets DOM variables for that element using a key value pair. So now you have a UL element with a class of my-new-list.

$('<ul/>', {'class':'my-new-list', 'html': items.join('')})

This is taking the array of LI elements created above joining the elements together in a string (with no delimiter in this case, .join('-') would have put a hyphen between each LI element) and assigning to the inner html of the UL.

$('<ul/>', {'class':'my-new-list', 'html': items.join('')}).appendTo('body');

Last but not least, it appends the newly created UL element with this child LI elements to the BODY element making it visible on the page.

Sign up to request clarification or add additional context in comments.

Comments

4
$('<ul/>', {
   'class': 'my-new-list',
   html: items.join('')
}).appendTo('body');

This simply creates a new UL element with a class of 'my-new-list' and the contents of items. It will create a structure like:

<ul class='my-new-list'>
<li id="key1">val1</li><li id="key2">val2</li><li id="key3">val3</li>
</ul>

This is simply short hand for:

$('<ul></ul>').attr('class', 'my-new-list').attr('html', items.join('')).appendTo('body');

Documentation: http://api.jquery.com/jQuery/#jQuery2

Comments

3

Check out the documentation for jQuery ($). Specifically, look at the part dealing with the overload jQuery( html, props ):

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

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

Further down there is more information:

As of jQuery 1.4, the second argument to jQuery() can accept a map consisting of a superset of the properties that can be passed to the .attr() method. Furthermore, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset. The name "class" must be quoted in the map since it is a JavaScript reserved word, and "className" cannot be used since it is not the correct attribute name.

Comments

1

See the jQuery documentation here. Specifically the section entitled:

Creating New Elements

This section contains details on the use of the jQuery( html, props ) overload, added in version 1.4. This is the overload used in your example. It takes an html string argument which is used to create a new DOM element and then adds the attributes contained in the props object argument.

Comments

1

That means you're appending a <ul> element with the my-new-list class to the body. The <li> items you've constructed in the items array are then added to the <ul>, so you'll end up with something like:

<ul class="my-new-list">
  <li id="key1">val1</li><li id="key2">val2</li>...
</ul>

Comments

1
$('<ul/>', {
   'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');

In jQuery, besides searching for DOM elements, you can also create them.

$('<ul/>') // or $('<ul></ul>')

This makes a new <ul> elements and returns it as a jQuery object.

The object passed as the 2nd parameter sets its attributes. Thus making this:

<ul class="my-new-list"><li id="one">O Hai</li></ul>

This <ul> is then appended to the body.

Comments

1

The part you don't understand is a completely different usage of the $ function. In most cases you use $ function as a selector which returns a set of jquery elements (dom nodes wrapped as jquery objects) which you can perform some kind of operation on.

In this case you are instead using the $ function to build DOM nodes (actually, jquery objects) and then those objects you can perform functions on, such as appendTo in the example shown.

It is pretty much equavalent to writing something like

var node = document.createElement("ul");
node.setAttribute("class", "my-new-list");
node.innerHTML = items.join('');

document.body.appendChild(node);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.