// Changing text content
$('#my-paragraph').text('Updated text content.');
// Changing HTML content
$('#my-paragraph').html('<strong>Updated</strong> text content with HTML.');
// Appending content
$('#my-paragraph').append(' Additional text.');
// Prepending content
$('#my-paragraph').prepend('Prepended text. ');
Modifying Element Attributes
You can also change the attributes of elements using jQuery.
HTML
<img id="my-image" src="/image.jpg" alt="Old Image">
jQuery
// Changing src attribute
$('#my-image').attr('src', 'new-image.jpg');
// Changing alt attribute
$('#my-image').attr('alt', 'New Image');
Adding and Removing Classes
jQuery makes it easy to add or remove CSS classes from elements.
HTML
<div id="my-div" class="box"></div>
jQuery
// Adding a class
$('#my-div').addClass('highlight');
// Removing a class
$('#my-div').removeClass('box');
// Toggling a class
$('#my-div').toggleClass('selected');
Handling Events
You can use jQuery to attach event handlers to elements.
HTML
<button id="my-button">Click Me</button>
jQuery
// Click event handler
$('#my-button').click(function() {
alert('Button clicked!');
});
// Mouseover event handler
$('#my-button').mouseover(function() {
$(this).text('Mouse over me!');
});
// Mouseout event handler
$('#my-button').mouseout(function() {
$(this).text('Click Me');
});
These are some basic examples of DOM manipulation with jQuery. jQuery provides many more methods and features that can be utilized for more advanced manipulation.
Find bout more visiting jQuery official website documentation.
More articles on this:
- How to implement event handling in jQuery
- How to select elements with jQuery
- How to use jquery document ready