What is it?
jQuery DOM manipulation methods let you dynamically create, insert, move, and remove HTML elements at runtime, updating the page without a full reload.
Why does it matter?
Dynamic content is the core of modern web UIs — adding items to a cart, inserting form rows, showing error messages, building accordions. jQuery makes all these operations readable and concise.
Learn how to create, insert, remove, and modify HTML elements using jQuery — append, prepend, before, after, remove, clone, and wrap.
Real-World Use Cases
- 🛒 Shopping cart items - append() a new cart item row when a product is added, remove() it when deleted, and update totals in the same call.
- 📝 Dynamic form builder - prepend(), append() and clone() let you add/remove form fields dynamically for multi-step forms.
- 💬 Chat message feed - append() new messages to a chat container and scrollTop() to the bottom — classic pattern for real-time UIs.
- 📋 Todo list - append() new tasks, remove() completed ones, toggleClass() to mark done — complete CRUD UI in jQuery.
Creating and Inserting Elements
// Create a new element
var $li = $('New Item ');
// Insert INSIDE an element
$('#list').append($li); // after last child
$('#list').prepend($li); // before first child
$li.appendTo('#list'); // same as append, different syntax
// Insert OUTSIDE (beside) an element
$('#item2').before('Before item 2 ');
$('#item2').after('After item 2 ');
Removing and Replacing Elements
// Remove permanently
$('.old-item').remove();
$('.temp').remove(); // also removes event listeners
// Empty (clear children but keep element)
$('#container').empty(); // removes all children
// Replace an element with something new
$('#old').replaceWith('Replaced!');
// Clone an element (with true = clone events too)
var $copy = $('#template').clone(true);
$('#list').append($copy);
Modifying HTML and CSS
// HTML content
$('#box').html('Updated');
$('#box').html(); // get current HTML
// Classes
$('#btn').addClass('active');
$('#btn').removeClass('active');
$('#btn').toggleClass('active');
$('#btn').hasClass('active'); // returns true/false
// CSS properties
$('#box').css('background-color', '#3b82f6');
$('#box').css({ color: 'white', padding: '1rem' }); // multiple
// Data attributes
$('#card').data('user-id', 42);
$('#card').data('user-id'); // get
Q: What is the difference between .remove() and .detach()?
.remove() deletes the element AND its event listeners. .detach() removes it from the DOM but keeps the element and its events in memory so you can re-insert it later. Use .detach() when you plan to move an element; use .remove() when you want it gone permanently.
Comments (0)
No comments yet. Be the first!
Leave a Comment