JQuery

Jquery HTML Manipulation

jQuery HTML Manipulation

What Does It Mean?

  • Changing or retrieving content (text, HTML) inside elements.

  • Adding, removing, or modifying attributes and classes.

  • Creating or removing elements dynamically.


Common jQuery Methods for HTML Manipulation

Method Description Example
.html() Get or set the HTML content inside an element $('#box').html('<b>Bold Text</b>')
.text() Get or set the text content (no HTML) $('#box').text('Plain Text')
.val() Get or set the value of form elements $('#input').val('New value')
.attr() Get or set the value of attributes $('img').attr('src', 'newimage.jpg')
.removeAttr() Remove an attribute $('input').removeAttr('disabled')
.addClass() Add a CSS class to elements $('p').addClass('highlight')
.removeClass() Remove a CSS class $('p').removeClass('highlight')
.toggleClass() Toggle a CSS class (add if missing, remove if present) $('p').toggleClass('active')
.append() Add HTML or elements inside at the end $('#list').append('<li>New Item</li>')
.prepend() Add HTML or elements inside at the beginning $('#list').prepend('<li>First Item</li>')
.remove() Remove elements from the DOM $('.old').remove()

Examples

Change HTML inside a div

js
$('#content').html('<h2>Welcome!</h2><p>This is new content.</p>');

Get text content from a paragraph

js
let text = $('#intro').text();
console.log(text);

Change the source of an image

js
$('img#logo').attr('src', 'logo2.png');

Add a class to highlight paragraphs

js
$('p').addClass('highlight');

Remove a class

js
$('p').removeClass('highlight');

Append a new item to a list

js
$('#myList').append('<li>New Item</li>');

Remove all elements with class “obsolete”

js
$('.obsolete').remove();

Summary

jQuery’s HTML manipulation methods let you dynamically update your page content and appearance easily — essential for interactive web applications.

Leave a Reply

Your email address will not be published. Required fields are marked *