Skip to content

jQuery DOM Manipulation

DOM (Document Object Model) manipulation is one of jQuery's core features. With jQuery, you can easily select, create, modify, and delete HTML elements. This chapter covers how to perform various DOM operations using jQuery.

Getting and Setting Element Content

1. text() Method

Get or set element text content (without HTML tags):

javascript
// Get text content
var text = $('#myElement').text();

// Set text content
$('#myElement').text('New text content');

// Set text content using function
$('#myElement').text(function(index, currentText) {
    return 'Element ' + index + ' new text: ' + currentText;
});

2. html() Method

Get or set element HTML content (including HTML tags):

javascript
// Get HTML content
var html = $('#myElement').html();

// Set HTML content
$('#myElement').html('<strong>New HTML content</strong>');

// Set HTML content using function
$('#myElement').html(function(index, currentHtml) {
    return '<em>Element ' + index + ' new HTML: ' + currentHtml + '</em>';
});

3. val() Method

Get or set form element values:

javascript
// Get form element value
var value = $('#myInput').val();

// Set form element value
$('#myInput').val('New value');

// Get checkbox checked state
var isChecked = $('#myCheckbox').val();

// Get dropdown selected value
var selectedValue = $('#mySelect').val();

Attribute Operations

1. attr() Method

Get or set element attributes:

javascript
// Get attribute value
var title = $('#myElement').attr('title');

// Set attribute value
$('#myElement').attr('title', 'New title');

// Set multiple attributes
$('#myElement').attr({
    'title': 'New title',
    'class': 'newClass',
    'data-id': '123'
});

// Set attribute using function
$('#myElement').attr('title', function(index, currentValue) {
    return 'Element ' + index + ' new title: ' + currentValue;
});

2. removeAttr() Method

Remove element attributes:

javascript
// Remove single attribute
$('#myElement').removeAttr('title');

// Remove multiple attributes
$('#myElement').removeAttr('title class data-id');

3. prop() Method

Get or set element properties (recommended for boolean properties):

javascript
// Get property value
var checked = $('#myCheckbox').prop('checked');

// Set property value
$('#myCheckbox').prop('checked', true);

// Set multiple properties
$('#myElement').prop({
    'disabled': true,
    'readonly': true
});

CSS Class and Style Operations

1. addClass() Method

Add CSS classes to elements:

javascript
// Add single class
$('#myElement').addClass('newClass');

// Add multiple classes
$('#myElement').addClass('class1 class2 class3');

// Add class using function
$('#myElement').addClass(function(index, currentClass) {
    return 'class-' + index;
});

2. removeClass() Method

Remove CSS classes from elements:

javascript
// Remove single class
$('#myElement').removeClass('oldClass');

// Remove multiple classes
$('#myElement').removeClass('class1 class2');

// Remove all classes
$('#myElement').removeClass();

// Remove class using function
$('#myElement').removeClass(function(index, currentClass) {
    return currentClass === 'toBeRemoved' ? 'toBeRemoved' : '';
});

3. toggleClass() Method

Toggle element CSS classes:

javascript
// Toggle class
$('#myElement').toggleClass('highlight');

// Toggle multiple classes
$('#myElement').toggleClass('class1 class2');

// Toggle class based on condition
$('#myElement').toggleClass('highlight', someCondition);

4. hasClass() Method

Check if element contains specified CSS class:

javascript
// Check if contains class
if ($('#myElement').hasClass('highlight')) {
    console.log('Element contains highlight class');
}

5. css() Method

Get or set element CSS styles:

javascript
// Get single CSS property
var color = $('#myElement').css('color');

// Get multiple CSS properties
var styles = $('#myElement').css(['color', 'font-size', 'background-color']);

// Set single CSS property
$('#myElement').css('color', 'red');

// Set multiple CSS properties
$('#myElement').css({
    'color': 'red',
    'font-size': '16px',
    'background-color': '#f0f0f0'
});

Element Dimensions and Position

1. width() and height() Methods

Get or set element width and height:

javascript
// Get width and height
var width = $('#myElement').width();
var height = $('#myElement').height();

// Set width and height
$('#myElement').width(200);
$('#myElement').height(100);

// Set using strings
$('#myElement').width('50%');
$('#myElement').height('auto');

2. innerWidth() and innerHeight() Methods

Get or set element inner width and height (including padding):

javascript
// Get inner dimensions
var innerWidth = $('#myElement').innerWidth();
var innerHeight = $('#myElement').innerHeight();

// Set inner dimensions
$('#myElement').innerWidth(200);
$('#myElement').innerHeight(100);

3. outerWidth() and outerHeight() Methods

Get or set element outer width and height (including padding and border):

javascript
// Get outer dimensions
var outerWidth = $('#myElement').outerWidth();
var outerHeight = $('#myElement').outerHeight();

// Get outer dimensions including margin
var outerWidthWithMargin = $('#myElement').outerWidth(true);
var outerHeightWithMargin = $('#myElement').outerHeight(true);

DOM Element Operations

1. Creating Elements

Create new elements using jQuery:

javascript
// Create simple element
var $div = $('<div>');

// Create element with content
var $p = $('<p>This is a paragraph</p>');

// Create element with attributes
var $input = $('<input type="text" class="form-control" placeholder="Enter content">');

// Create complex element structure
var $complex = $('<div class="container"><h2>Title</h2><p>Content</p></div>');

2. Inserting Elements

append() Method

Insert content at the end inside an element:

javascript
// Insert content at end
$('#myElement').append('<p>New paragraph</p>');

// Insert existing element
$('#myElement').append($('#anotherElement'));

// Insert multiple contents
$('#myElement').append('<p>Paragraph 1</p>', '<p>Paragraph 2</p>');

prepend() Method

Insert content at the beginning inside an element:

javascript
// Insert content at beginning
$('#myElement').prepend('<p>New paragraph</p>');

// Insert existing element
$('#myElement').prepend($('#anotherElement'));

after() Method

Insert content after an element:

javascript
// Insert content after element
$('#myElement').after('<p>New paragraph</p>');

// Insert existing element
$('#myElement').after($('#anotherElement'));

before() Method

Insert content before an element:

javascript
// Insert content before element
$('#myElement').before('<p>New paragraph</p>');

// Insert existing element
$('#myElement').before($('#anotherElement'));

3. Removing Elements

remove() Method

Remove element along with all children and events:

javascript
// Remove element
$('#myElement').remove();

// Remove elements based on condition
$('p').remove('.highlight');

detach() Method

Remove element but preserve data and events:

javascript
// Remove element preserving data and events
var $element = $('#myElement').detach();

// Re-insert element later
$('body').append($element);

empty() Method

Clear element content:

javascript
// Clear element content
$('#myElement').empty();

4. Replacing Elements

replaceWith() Method

Replace element:

javascript
// Replace element
$('#myElement').replaceWith('<p>New content</p>');

// Replace with existing element
$('#myElement').replaceWith($('#anotherElement'));

replaceAll() Method

Replace all matching elements:

javascript
// Replace all matching elements
$('<p>New content</p>').replaceAll('.oldClass');

Element Traversal

1. Parent Element Traversal

parent() Method

Get direct parent element:

javascript
// Get direct parent
var $parent = $('#myElement').parent();

// Get parent matching selector
var $specificParent = $('#myElement').parent('.container');

parents() Method

Get all ancestor elements:

javascript
// Get all ancestors
var $parents = $('#myElement').parents();

// Get ancestors matching selector
var $specificParents = $('#myElement').parents('.container');

2. Child Element Traversal

children() Method

Get direct child elements:

javascript
// Get all direct children
var $children = $('#myElement').children();

// Get children matching selector
var $specificChildren = $('#myElement').children('.item');

find() Method

Get all descendant elements:

javascript
// Get all descendants
var $descendants = $('#myElement').find('*');

// Get descendants matching selector
var $specificDescendants = $('#myElement').find('.item');

3. Sibling Element Traversal

siblings() Method

Get all sibling elements:

javascript
// Get all siblings
var $siblings = $('#myElement').siblings();

// Get siblings matching selector
var $specificSiblings = $('#myElement').siblings('.item');

next() and prev() Methods

Get next or previous sibling element:

javascript
// Get next sibling
var $next = $('#myElement').next();

// Get previous sibling
var $prev = $('#myElement').prev();

// Get with selector
var $specificNext = $('#myElement').next('.item');
var $specificPrev = $('#myElement').prev('.item');

nextAll() and prevAll() Methods

Get all following or preceding sibling elements:

javascript
// Get all following siblings
var $nextAll = $('#myElement').nextAll();

// Get all preceding siblings
var $prevAll = $('#myElement').prevAll();

Cloning Elements

clone() Method

Clone elements:

javascript
// Clone element (without events and data)
var $clone = $('#myElement').clone();

// Clone element (with events and data)
var $cloneWithData = $('#myElement').clone(true);

// Insert cloned element into page
$('body').append($clone);

Complete Example

Here's a complete example demonstrating jQuery DOM manipulation:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery DOM Manipulation Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .container { border: 1px solid #ccc; padding: 20px; margin: 10px 0; }
        .highlight { background-color: yellow; }
        .new-class { color: red; font-weight: bold; }
        .item { margin: 5px 0; padding: 5px; border: 1px solid #eee; }
    </style>
</head>
<body>
    <h1>jQuery DOM Manipulation Example</h1>
    
    <div class="container">
        <h2>Content Operations</h2>
        <p id="textContent">This is original text content</p>
        <div id="htmlContent">This contains <strong>HTML</strong> content</div>
        <input type="text" id="inputValue" value="Original value">
        <button id="updateContent">Update Content</button>
    </div>
    
    <div class="container">
        <h2>Attribute Operations</h2>
        <div id="attrElement" title="Original title" class="old-class">Attribute example</div>
        <button id="updateAttr">Update Attributes</button>
    </div>
    
    <div class="container">
        <h2>Element Insertion and Removal</h2>
        <div id="insertContainer">
            <p>Original paragraph</p>
        </div>
        <button id="addElement">Add Element</button>
        <button id="removeElement">Remove Element</button>
    </div>
    
    <script>
        $(function() {
            // Content operations
            $('#updateContent').click(function() {
                $('#textContent').text('This is updated text content');
                $('#htmlContent').html('This is updated <em>HTML</em> content');
                $('#inputValue').val('Updated value');
            });
            
            // Attribute operations
            $('#updateAttr').click(function() {
                $('#attrElement').attr('title', 'Updated title');
                $('#attrElement').addClass('new-class');
                $('#attrElement').attr({
                    'data-id': '123',
                    'data-name': 'example'
                });
            });
            
            // Element insertion and removal
            $('#addElement').click(function() {
                $('#insertContainer').append('<p class="item">Appended paragraph</p>');
                $('#insertContainer').prepend('<p class="item">Prepended paragraph</p>');
            });
            
            $('#removeElement').click(function() {
                $('#insertContainer p:last').remove();
            });
        });
    </script>
</body>
</html>

Through this chapter, you should have mastered how to perform various DOM operations using jQuery. In the next chapter, we'll learn about jQuery event handling.

Content is for learning and research only.