Building Structure

We should take few minutes to look at operating on the structure of the document. We'll use jQuery to do this. We'll start with adding a list of prime numbers to the web page. First, we need to have a destination for them:

<div id="prime-container">
  <p>Our primes:</p>
  <ul id="prime-list">
  </ul>
</div>

Now the code to add some primes to that list:

function addPrimes( primes ) {
    primes.forEach(function(p) {
             $('<li>').text(p).appendTo('#prime-list')
         });
}

addPrimes( [2, 3, 5, 7, 11, 13, 17] );

Here it is:

Our primes:

The complete example is interesting, but I want to focus on one small part of it, namely:

   $('<li>').text(p).appendTo('#prime-list');

You might wonder what the '<li>' does as the argument of the jQuery function, since it's not a CSS selector. (li is a valid selector for all list items, but not <li>.) What happens is that jQuery creates the given element (in this case, an li), but it is not (yet) attached to the document. Here, we attach it to the document with the jQuery appendTo method, after giving it some text, namely one of our prime numbers.

An alternative way to do this is to build the entire list up and only attach it to the document at the end. This is more efficient, since the document only has to be re-rendered once for the list, as opposed to once for each element.

  <div id="prime-container2">
    <p>Our primes:</p>
  </div>

Here's the variant JS/JQ code:

function addPrimes2(primes) {
    var $ul = $('<ul>');  // create a UL element
    primes.forEach(function (p) {
        $('<li>').text(p).appendTo($ul); // create an LI and append it to the UL
    });
    $ul.appendTo('#prime-container2');  // append the UL to the DIV
}
addPrimes2( [2, 3, 5, 7, 11, 13, 17] );

Here it is:

Another list of our primes:

Here, we create a UL element, then create a bunch of LI elements, appending each of them to the UL element, and finally graft the whole thing onto the tree (the page).