General jQuery Tips from Class

by Dan Wahlin

HTML

<span id="output"></span>
<br /><br />
<div id="container" style="background-color:#efefef;height:150px;">
  Container div
</div>

JavaScript

$(document).ready(function() {
    //cache nodes since they may be re-used
    var $container = $('#container');
    var $output = $('#output');
    
    //check if container exists already in DOM
    if ($container.length) {
        $output.text('Container exists!');
    }
    
    //Add attributes without string concatenation
    $('<div />', {
        style: 'background:green;color:white;font-weight:bold;',  
        height:'25px',
        text: 'Dynamically added div'})
    .appendTo($container);
    
    //efficient DOM manipulation
    //add multiple children
    //JavaScript for loop is generally faster than jQuery each() loop
    //but showing how an each() can be used on an array
    var ids = [1,2,3,4,5];
    var children = '';
    $.each(ids, function(index, val) {
        children += '<div id="Div' + val + '">Div ' + val + '</div>';
    });
    $container.append(children);
    
    //Different techniques for finding nodes within a context 
    //(starting point)
    var $div1 = $container.find('#Div1');
    var $div1Alternate = $('#Div1', $container);
    alert($div1.length);
    
    
    
    
    
});