Skip to content
jQuery DOM Manipulation — Complete Content & Element Control Guide

jQuery DOM Manipulation — Complete Content & Element Control Guide

DodaTech Updated Jun 6, 2026 10 min read

jQuery DOM manipulation lets you read and change page content, attributes, styles, and structure with simple, chainable methods that work consistently across all browsers.

What You’ll Learn

  • How to get and set text, HTML, form values, and attributes
  • How to add, move, and remove elements
  • How to manage CSS classes and inline styles
  • How to work with element dimensions and position
  • How to use HTML5 data attributes
  • Common DOM manipulation mistakes and best practices

Why DOM Manipulation Matters

The DOM is the bridge between your JavaScript and what the user sees. Every time you change text on a page, highlight an error, or update a counter, you’re manipulating the DOM. Think of it like renovating a house — jQuery’s DOM methods are your hammer, saw, and measuring tape. In DodaTech’s Durga Antivirus Pro, DOM manipulation updates threat counts in real-time, shows/hides alert panels, and dynamically populates scan result tables without full page reloads.

DOM Manipulation Learning Path

    flowchart TD
  A[jQuery Selectors] --> B[jQuery DOM: You Are Here]
  B --> C[Get/Set Content]
  B --> D[Add/Remove Elements]
  B --> E[CSS & Classes]
  B --> F[Dimensions & Position]
  C --> G[jQuery Effects]
  D --> G
  E --> G
  
🔧
Prerequisites: https://tutorials.dodatech.com/frameworks/jquery/jquery-selectors/ (you need to find elements before manipulating them), HTML structure knowledge, and basic CSS property familiarity.

Getting and Setting Content

Text Content (.text())

.text() reads or writes plain text, stripping out HTML tags. It also escapes HTML entities, making it safe for user-generated content:

// GET: returns all text content (HTML tags removed)
var text = $("p").text();
// If <p>Hello <strong>World</strong></p>, returns "Hello World"

// SET: replaces text (HTML is escaped automatically — prevents XSS!)
$("p").text("Hello <World>");
// Displays: Hello <World> (the < > are shown literally)

// SET on all matched elements
$("li").text("Updated Item");
// Every <li> now says "Updated Item"

Why use .text() over .html()? Security. If a user submits text containing <script>alert('xss')</script>, .text() displays it harmlessly. .html() would execute the script.

HTML Content (.html())

.html() reads or writes HTML — tags are interpreted, not escaped:

// GET: returns inner HTML of the FIRST matched element only
var html = $("div").html();

// SET: interprets HTML tags
$("div").html("<strong>Bold text</strong>");
// Renders as: **Bold text**

// WARNING: Only affects the first element in the set
$("li").html("Same content");  // Only first <li> changes!

Important: .html() when getting returns only the first element’s content. To get all, use .each():

$("li").each(function() {
    console.log($(this).html());
});

Form Values (.val())

.val() gets or sets form field values:

// GET
var name = $("input#name").val();
var selectedCountry = $("select#country").val();

// SET
$("input#name").val("Alice");
$("select#country").val("us");
$("input#agree").prop("checked", true);  // Checkboxes use .prop(), not .val()

// Serialize entire form to query string
var formData = $("form").serialize();
// "name=Alice&email=alice%40test.com&age=30"

// Serialize to array of objects
var formArray = $("form").serializeArray();
// [{name: "name", value: "Alice"}, {name: "email", value: "alice@test.com"}]

Attributes (.attr())

Attributes are values defined in the HTML (like src, href, alt):

// GET
var src = $("img").attr("src");
var href = $("a").attr("href");

// SET (single)
$("img").attr("src", "new-image.jpg");
$("a").attr("href", "https://example.com");

// SET (multiple at once)
$("img").attr({
    src: "photo.jpg",
    alt: "A beautiful photo",
    title: "My Photo"
});

// REMOVE
$("a").removeAttr("target");

Properties vs Attributes (.prop() vs .attr())

This is a common source of confusion. Some element states are properties (dynamic, change at runtime) while others are attributes (defined in HTML):

// Use .prop() for boolean properties that change dynamically
$("input").prop("disabled", true);    // Disable an input
$("input").prop("checked", true);     // Check a checkbox
$("select option").prop("selected", true);  // Select an option

// Use .attr() for HTML attributes
$("img").attr("src", "photo.jpg");    // src attribute
$("a").attr("href", "/page");         // href attribute
$("div").attr("data-id", "42");       // Custom data attributes

// Rule of thumb:
// .prop() → disabled, checked, selected, readOnly, indeterminate
// .attr() → href, src, alt, title, data-*, custom attributes

Why the distinction? Consider a checkbox. The HTML might say <input type="checkbox" checked>. The attribute checked stays in the HTML forever. But the property checked changes when the user clicks it. .prop("checked") reads the current state; .attr("checked") reads the initial HTML state.

Adding Elements

Insert Inside an Element

// As last child (most common)
$("ul").append("<li>New item</li>");

// As first child
$("ul").prepend("<li>First item</li>");

// Create element first, then append
var $newItem = $("<li>").text("Dynamic").addClass("new");
$("ul").append($newItem);

Insert Outside an Element (as Sibling)

$("ul").after("<p>After the list</p>");   // Directly after
$("ul").before("<p>Before the list</p>"); // Directly before

Create Elements from HTML Objects

// Create a <div> with properties, then add to body
$("<div>", {
    id: "newDiv",
    class: "box highlight",
    text: "Created by jQuery!",
    css: { color: "red" },
    click: function() {
        alert("You clicked the new div!");
    }
}).appendTo("body");

Move Existing Elements

$("#item2").insertBefore("#item1");   // Move item2 before item1
$("#item2").insertAfter("#item1");    // Move item2 after item1
$("#item2").appendTo("#newParent");   // Move to new parent

Moving elements is like physically picking up a box and placing it somewhere else. The element isn’t copied — it’s relocated.

Removing Elements

// .remove() — deletes the element AND its jQuery data/events
$("#temp").remove();
$("li").remove(".old");              // Remove only li.old elements

// .empty() — removes children, keeps the element itself
$("#container").empty();

// .detach() — removes from DOM but KEEPS data/events (can reattach)
var $detached = $("#item").detach();
// ... later ...
$("#container").append($detached);  // Events still work!

// .unwrap() — removes the parent element
$("span").unwrap();  // <p><span>Hi</span></p> → <span>Hi</span>

The difference between .remove() and .detach() is like throwing away a file vs putting it in a drawer. .remove() destroys everything permanently. .detach() preserves the element’s data so you can reuse it later.

CSS Classes

Managing classes is cleaner than manipulating inline styles:

// Add one or more classes
$("p").addClass("highlight");
$("p").addClass("highlight active");     // Multiple at once

// Remove class
$("p").removeClass("highlight");
$("p").removeClass();                    // Remove ALL classes

// Toggle (add if absent, remove if present)
$("p").toggleClass("active");

// Check if class exists
if ($("p").hasClass("active")) {
    console.log("Has the active class");
}

// Conditional toggle
$("p").toggleClass("active", isActive);
// If isActive is true, class is added. If false, removed.

Why prefer .addClass() over .css()? Classes keep styling in your CSS file where it belongs. If you later change the highlight color, you edit one CSS rule instead of hunting through 50 JavaScript files.

CSS Properties

Use .css() for direct inline styles when classes aren’t practical:

// GET computed value
var color = $("p").css("color");
var fontSize = $("p").css("font-size");
// Accepts both camelCase and kebab-case:
var fontSizeAlt = $("p").css("fontSize");

// SET single property
$("p").css("color", "red");
$("p").css("font-size", "16px");

// SET multiple properties at once
$("p").css({
    color: "red",
    "font-size": "16px",
    backgroundColor: "#f0f0f0",
    padding: "10px"
});

JavaScript vs jQuery: DOM Manipulation

TaskVanilla JavaScriptjQuery
Set textel.textContent = "Hi"$el.text("Hi")
Set HTMLel.innerHTML = "<b>Hi</b>"$el.html("<b>Hi</b>")
Add classel.classList.add("x")$el.addClass("x")
Remove elementel.remove()$el.remove()
Append childel.appendChild(child)$el.append(child)
Get form valueel.value$el.val()

Dimensions

// Content area (no padding, border, margin)
var w = $("div").width();
var h = $("div").height();

// Inner (content + padding)
var ih = $("div").innerHeight();

// Outer (content + padding + border)
var oh = $("div").outerHeight();
var ohWithMargin = $("div").outerHeight(true);  // Include margin

// SET dimensions
$("div").width(200);
$("div").height("50%");

// Document and window dimensions
var docHeight = $(document).height();
var winWidth = $(window).width();

// Scroll position
var scrollTop = $(window).scrollTop();
$(window).scrollTop(0);  // Scroll to top

// Offset (position relative to document)
var offset = $("div").offset();
console.log("Top:", offset.top, "Left:", offset.left);

// Position (relative to offset parent)
var pos = $("div").position();

Data Attributes

HTML5 data-* attributes store custom data on elements. jQuery’s .data() method reads them:

// HTML: <div data-user-id="42" data-user-info='{"name":"Alice"}'>
$("div").data("userId");    // Returns 42 (number, not string!)
$("div").data("userInfo");  // Returns {name: "Alice"} (auto-parsed JSON!)

// SET data (stored in memory, not in DOM attribute)
$("div").data("lastAccess", Date.now());

// REMOVE
$("div").removeData("userId");

Important: .data() reads the HTML attribute only on the first access and then caches it in memory. Subsequent reads use the cache. If you need to update the actual DOM attribute, use .attr("data-user-id", "43").

Common Mistakes

1. Using .html() When .text() Is Safer

For user-generated content, always use .text() — it escapes HTML and prevents XSS attacks. .html() interprets strings as HTML.

2. Forgetting .html() Only Returns the First Element

var html = $("li").html();  // Only first <li>'s HTML
// Use .each() to get all:
$("li").each(function() {
    console.log($(this).html());
});

3. Removing Elements Loses Events

.remove() destroys jQuery data and events. Use .detach() if you plan to re-insert the element.

4. Confusing .attr() and .prop()

For checked, disabled, selected, use .prop(). For href, src, data-*, use .attr().

5. Setting CSS Without Units

// WRONG — no unit specified
$("div").css("width", 100);     // May work in some browsers
$("div").css("width", "100");   // Missing unit — ignored silently!

// RIGHT
$("div").css("width", "100px");
$("div").css("width", "50%");

6. Using .append() When You Meant .after()

.append() adds inside (as last child). .after() adds outside (as sibling). They’re different:

$("ul").append("<li>Inside</li>");   // <ul><li>Inside</li></ul>
$("ul").after("<p>Outside</p>");     // <ul>...</ul><p>Outside</p>

Practice Questions

1. What’s the difference between .text() and .html()?

.text() reads/sets plain text (HTML tags are escaped). .html() reads/sets HTML (tags are interpreted). Use .text() for user input to prevent XSS.

2. When should you use .detach() instead of .remove()?

Use .detach() when you plan to reinsert the element later, because it preserves jQuery data and event handlers. .remove() destroys everything.

3. How do you add multiple CSS properties at once?

$("div").css({
    color: "red",
    backgroundColor: "blue",
    padding: "10px"
});

4. Challenge: Build a function that takes an array of objects and renders a table. Each object has name, age, email. The function should create <table> with <thead> and <tbody>, append rows, and add alternating row classes.

Answer
function renderTable(data, container) {
    var $table = $("<table>").addClass("data-table");
    var $thead = $("<thead>").append("<tr><th>Name</th><th>Age</th><th>Email</th></tr>");
    var $tbody = $("<tbody>");
    $.each(data, function(i, item) {
        var cls = i % 2 === 0 ? "even" : "odd";
        $("<tr>").addClass(cls).append(
            $("<td>").text(item.name),
            $("<td>").text(item.age),
            $("<td>").text(item.email)
        ).appendTo($tbody);
    });
    $table.append($thead, $tbody);
    $(container).empty().append($table);
}

FAQ

What is the difference between .append() and .after()?
.append() adds content inside the element as the last child. .after() adds content outside the element as a sibling after it.
What does .detach() do that .remove() doesn’t?
.detach() keeps all jQuery data and event handlers bound to the element so you can reattach it later. .remove() destroys everything.
How do I get element width including margin?
Use .outerWidth(true). Without true, it includes padding and border but not margin.
What’s the difference between .css() and .addClass()?
.css() sets inline styles directly. .addClass() adds a class from a stylesheet. Prefer .addClass() for maintainability.
How does .data() work with HTML5 data attributes?
.data("userId") reads data-user-id on first access, auto-converts to the correct type, and caches the value. Subsequent reads use the cache, not the DOM.
Can I use .html() to remove all content?
Yes. .html("") empties the element, same as .empty().

Try It Yourself

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM Manipulation Sandbox</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 600px; margin: 40px auto; }
        table { border-collapse: collapse; width: 100%; margin: 20px 0; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a73e8; color: white; }
        input, select { padding: 6px; margin: 4px; }
        button { padding: 8px 16px; cursor: pointer; }
        .controls { background: #f5f5f5; padding: 16px; border-radius: 8px; margin: 16px 0; }
    </style>
</head>
<body>
    <h1>Dynamic Table Builder</h1>
    <div class="controls">
        <input type="text" id="itemName" placeholder="Item name">
        <input type="number" id="itemQty" placeholder="Qty" value="1">
        <input type="number" id="itemPrice" placeholder="Price" value="0.00" step="0.01">
        <button id="addRow">Add Row</button>
        <button id="clearRows">Clear All</button>
    </div>
    <table id="dataTable">
        <thead>
            <tr><th>Item</th><th>Qty</th><th>Price</th><th>Total</th><th>Action</th></tr>
        </thead>
        <tbody></tbody>
        <tfoot>
            <tr><th colspan="3">Grand Total</th><th id="grandTotal">$0.00</th><th></th></tr>
        </tfoot>
    </table>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $(function() {
            function updateTotal() {
                var total = 0;
                $("#dataTable tbody tr").each(function() {
                    var qty = parseFloat($(this).find(".qty").text()) || 0;
                    var price = parseFloat($(this).find(".price").text()) || 0;
                    var lineTotal = qty * price;
                    $(this).find(".lineTotal").text("$" + lineTotal.toFixed(2));
                    total += lineTotal;
                });
                $("#grandTotal").text("$" + total.toFixed(2));
            }

            $("#addRow").click(function() {
                var name = $("#itemName").val().trim();
                if (!name) return;
                var $row = $("<tr>");
                $row.append($("<td>").addClass("name").text(name));
                $row.append($("<td>").addClass("qty").text($("#itemQty").val()));
                $row.append($("<td>").addClass("price").text($("#itemPrice").val()));
                $row.append($("<td>").addClass("lineTotal").text("$0.00"));
                $row.append($("<td>").html('<button class="deleteRow" style="background:#d32f2f;color:white;border:none;padding:4px 8px;cursor:pointer;">✕</button>'));
                $("#dataTable tbody").append($row);
                updateTotal();
                $("#itemName").val("").focus();
            });

            $("#dataTable").on("click", ".deleteRow", function() {
                $(this).closest("tr").remove();
                updateTotal();
            });

            $("#clearRows").click(function() {
                $("#dataTable tbody").empty();
                updateTotal();
            });
        });
    </script>
</body>
</html>

What’s Next

TopicDescription
https://tutorials.dodatech.com/frameworks/jquery/jquery-effects/Animate and transition DOM elements
https://tutorials.dodatech.com/frameworks/jquery/jquery-traversing/Navigate the DOM tree to find related elements
https://tutorials.dodatech.com/frameworks/jquery/jquery-ajax/Load and send data without page reloads
JavaScriptJavaScript fundamentals for DOM scripting
CSSCSS properties and class-based styling

What’s Next

Congratulations on completing this Jquery Dom tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro