DOM Manipulation

This section documents jQuery 3.x (the current major line — no specific patch version is pinned). This content was generated with the assistance of AI and should be verified against the official jQuery API reference before being relied on in production, since API details and deprecations continue to change between releases.

jQuery is legacy-leaning: modern browsers implement native equivalents for almost everything it does (querySelectorAll, classList, fetch, addEventListener, append/prepend/remove, the Web Animations API), and most current stacks — Bootstrap 5 included — have dropped it. Prefer the native APIs for new work; this reference is aimed at reading, maintaining, or incrementally migrating code that already uses jQuery. Every page ends with a Modern equivalent note pointing at the native replacement.

This section’s bibliography lists the reference material consulted while preparing these pages.

jQuery’s manipulation methods change the content and structure of matched elements. Most act on every element in the set and return the set, so they chain.

Reading and writing content

$('#box').html();                       // GET: inner HTML of the FIRST element
$('#box').html('<b>Hi</b>');            // SET: inner HTML of EVERY element (parses HTML)

$('#box').text();                       // GET: combined text of ALL elements
$('#box').text('<b>Hi</b>');            // SET: assigns as literal text (escapes < >)

$('#name').val();                       // GET: value of the first form control
$('#name').val('Ada');                  // SET: value of every matched control
$('#tags').val(['a', 'b']);             // multi-select: select these options

A getter reads the first element; a setter writes them all. .text() is HTML-safe (it sets textContent); .html() parses its argument as markup, so never pass unsanitized user input to it.

Inserting elements

Inside a target

$('#list').append('<li>last</li>');     // as the last child of #list
$('#list').prepend('<li>first</li>');   // as the first child of #list

$('<li>moved</li>').appendTo('#list');  // same as append, target/source swapped
$('<li>moved</li>').prependTo('#list'); // same as prepend, swapped

a.append(b) reads "put b inside a"; b.appendTo(a) reads "put b inside a" from b’s side — use whichever makes the chain read better.

Outside a target

$('#anchor').before('<hr>');            // as a preceding sibling
$('#anchor').after('<hr>');             // as a following sibling
$('<hr>').insertBefore('#anchor');      // same as before, swapped
$('<hr>').insertAfter('#anchor');       // same as after, swapped

Wrapping

$('.field').wrap('<div class="row"></div>');   // wrap EACH element individually
$('.field').wrapAll('<div class="row"></div>'); // wrap the whole set in ONE wrapper
$('.field').wrapInner('<span></span>');          // wrap each element's CONTENTS
$('.field').unwrap();                            // remove each element's parent, keep the element

Removing elements

$('#tmp').remove();     // detach from the DOM AND discard jQuery data / event handlers
$('#tmp').detach();     // detach but KEEP data / handlers, so it can be re-inserted
$('#tmp').empty();      // keep #tmp, delete all of its children

Use .detach() when you will re-insert the same nodes (their bound events still work); use .remove() when you are done with them — it frees the associated event handlers and .data() to avoid a leak.

const $row = $('#row').detach();       // pull it out, handlers intact
// ... reorder, measure, whatever ...
$row.appendTo('#table tbody');         // put it back, still clickable

Cloning and replacing

$('#tpl').clone();          // deep copy of the elements, WITHOUT event handlers / data
$('#tpl').clone(true);      // deep copy WITH event handlers and data copied too

$('#old').replaceWith('<div id="new"></div>');   // swap #old for the new markup
$('<div id="new"></div>').replaceAll('#old');    // same, source/target swapped

Creating elements

Pass an HTML string, or — clearer for setting several properties at once — a tag plus an attributes object. Referring to that second form in prose, it looks like $('<li>', { text: 'Item', class: 'new' }): the second argument is a plain object whose keys are jQuery methods (text, html, css, on, …​) or attribute names.

const $item = $('<li>', {
  text: 'Item 3',              // -> .text('Item 3')
  class: 'new',                // -> attribute class="new"
  'data-id': 42,               // -> attribute data-id="42"
  click: () => console.log('clicked')   // -> .on('click', ...)
});
$item.appendTo('#list');

Modern equivalent

el.innerHTML / el.textContent / input.value read and write content. Element.append, prepend, before, after, remove, and replaceWith are all native now and accept strings or nodes. el.cloneNode(true) deep-clones (never copies listeners). Create with document.createElement('li') then set properties, or use a <template>. See Web programming basics.