DOM Manipulation

Harry · 11 Sep 2026 · 10 views

Reading and Writing Content

$('#title').text('New Title');          // text only
$('#box').html('<b>Bold</b> text');      // HTML content
$('#box').val('typed-value');          // input value
console.log($('#box').text());           // read back

Without arguments these methods read; with an argument they write.

Adding and Removing Elements

$('#list').append('<li>End</li>');     // after last child
$('#list').prepend('<li>Start</li>');  // before first child
$('#masthead').after('<p>Below</p>');  // sibling after
$('#masthead').before('<p>Above</p>'); // sibling before

$('li.done').remove();                    // remove from DOM
$('div').empty();                         // remove contents only

Attributes and Classes

$('img').attr('src', 'new.png');
$('a').attr('href', 'https://example.com');

$('#btn').addClass('active');
$('#btn').removeClass('active');
$('#btn').toggleClass('active');
$('#btn').hasClass('active');        // boolean check

Styling

$('#box').css('color', 'red');
$('#box').css({ background: '#eee', padding: '10px' });
$('#nav').show();  $('#nav').hide();  $('#nav').toggle();

Key Points

  • text/html/val read and write content.
  • append/prepend/after/before place nodes precisely.
  • addClass/removeClass/toggleClass manage styling states.
  • Method calls chain: $el.hide().addClass('x').
Share this post:

Comments (0)

Please login or register to comment.