Preserving Chained Calls Using wrap()

Without the use of the jQuery wrap() function, it's difficult to use chained calls in certain situations.

by Adam Boduch

HTML

<h3>Links</h3>
<ul>

CSS

body {
    font: 0.8em Arial, Helvetica, sans-serif;
}

JavaScript

// Some link data. We need to turn these into a list
// of links in the DOM.
var links = [
    { name: "Link 1", href: "#l1" },
    { name: "Link 2", href: "#l2" },
    { name: "Link 3", href: "#l3" }
],

// The refence to the <ul/> element content we're going
// to generate.
$ul = $( "ul" ).empty();

// The first approach builds the <a/> element, and stores
// it in the $a variable. The <li/> element is then created,
// and now we can append the $a variable, then add the <li/>
// to the list.
$.each( links, function( i, link ) {
    var $a = $( "<a/>" ).attr( "title", link.name )
                        .attr( "href", link.href )
                        .text( link.name );
    $( "<li/>" ).append( $a ).appendTo( $ul );
});

$ul.empty();

// The second approach doesn't use any variables. Instead,
// it utilizes the wrap() function. It may seem counter-intuitive
// at first, but the <a/> element is added directly to the <ul/>.
// After that, happens, it wraps the <a/> in an <li/>, to generate
// the valid markup the browser expects.
$.each( links, function( i, link ) {
    $( "<a/>" ).attr( "title", link.name )
               .attr( "href", link.href )
               .text( link.name )
               .appendTo( $ul )
               .wrap( "<li/>" );
});