jQuery DOM manipulation methods summary and examples 

Joined:
02/21/2009
Posts:
131

January 27, 2012 12:38:53    Last update: January 27, 2012 12:39:46
A brief summary of jQuery DOM manipulation methods for reference.
  1. .before() and .insertBefore(): insert content before target element - as sibling.

    Examples:
    // insert summary before details
    $('#detail').before('<p><b>Summary</b></p>');
    $('<p><b>Summary</b></p>').insertBefore('#detail');
    
    // moves h2 before .detail if there's one h2 and one .detail
    // moves all h2 before .detail and copies all h2 to the rest of .detail
    // elements if there's more than one .detail
    $('.detail').before($('h2'));
    $('h2').insertBefore('.detail');
    

  2. .after() and .insertAfter(): insert content after target element - as sibling.

    Examples:
    // insert details after summary
    $('#summary').after('<p>Details</p>');
    $('<p>Details</p>').insertBefore('#summary');
    
    // moves .detail after h2 if there's one h2 and one .detail
    // moves all .detail after h2 and copies all .detail to the rest of h2
    // elements if there's more than one h2
    $('h2').after($('.detail'));
    $('.detail').insertAfter('h2');
    

  3. .prepend() and .prependTo(): insert content as first child of target element.

    Examples:
    // prepend caption to table
    $('table').prepend('<caption>Table Caption</caption>');
    $('<caption>Table Caption</caption>').prependTo('table');
    
    // Move h1 to the top of body 
    $('body').prepend($('h1'));
    $('h1').prependTo('body');
    

  4. .append() and .appendTo(): insert content as last child of target element.

    Examples:
    // append row to table
    $('table').append('<tr><td>more data</td></tr>');
    $('<tr><td>more data</td></tr>').appendTo('table');
    
    // Move footer to the bottom of body 
    $('body').append($('.footer'));
    $('.footer').appendTo('body');
    

Share |
| Comment  | Tags