jQuery & DOM Manipulation

Getting & Setting Content

15 min Lesson 10 of 30

Getting & Setting Content

jQuery provides powerful methods to read and modify the content of HTML elements. Understanding these methods is essential for dynamic web applications.

The .text() Method

The .text() method gets or sets the text content of elements, excluding HTML tags.

HTML:
<p id="intro">Welcome to <strong>jQuery</strong></p>
<button id="btn-get">Get Text</button>
<button id="btn-set">Set Text</button>
JavaScript:
// Getting text content
$("#btn-get").click(function() {
    var text = $("#intro").text();
    console.log(text); // "Welcome to jQuery"
});

// Setting text content
$("#btn-set").click(function() {
    $("#intro").text("New text content");
});
Tip: The .text() method automatically escapes HTML tags, making it safe for displaying user-generated content and preventing XSS attacks.

The .html() Method

The .html() method gets or sets the HTML content of elements, including tags.

HTML:
<div id="container">
    <p>Original content</p>
</div>
JavaScript:
// Getting HTML content
var html = $("#container").html();
console.log(html); // "<p>Original content</p>"

// Setting HTML content
$("#container").html("<h3>New Title</h3><p>New paragraph</p>");

// Appending HTML
var current = $("#container").html();
$("#container").html(current + "<p>Additional content</p>");
Warning: Be careful when using .html() with user input, as it can execute scripts. Always sanitize user data or use .text() instead.

The .val() Method

The .val() method gets or sets the value of form elements like inputs, textareas, and selects.

HTML:
<input type="text" id="username" value="JohnDoe">
<textarea id="message">Hello World</textarea>
<select id="country">
    <option value="us">United States</option>
    <option value="uk" selected>United Kingdom</option>
</select>
JavaScript:
// Getting values
var username = $("#username").val();        // "JohnDoe"
var message = $("#message").val();          // "Hello World"
var country = $("#country").val();          // "uk"

// Setting values
$("#username").val("JaneSmith");
$("#message").val("New message");
$("#country").val("us");

// Clearing input
$("#username").val("");

Working with Multiple Elements

When methods are called on multiple elements, getters return the value of the first element, while setters apply to all matched elements.

HTML:
<p class="item">First paragraph</p>
<p class="item">Second paragraph</p>
<p class="item">Third paragraph</p>
JavaScript:
// Getter returns first element only
var text = $(".item").text();
console.log(text); // "First paragraph"

// Setter applies to all elements
$(".item").text("All paragraphs updated");

// Now all three paragraphs have the same text

Using Callback Functions

Content methods can accept callback functions to set different values for each element based on its index and current value.

HTML:
<div class="box">Box</div>
<div class="box">Box</div>
<div class="box">Box</div>
JavaScript:
// Set different text for each element
$(".box").text(function(index, currentText) {
    return currentText + " " + (index + 1);
});
// Result: "Box 1", "Box 2", "Box 3"

// Update based on current content
$(".box").html(function(index, currentHtml) {
    return "<strong>" + currentHtml + "</strong>";
});

Practical Example: Dynamic Content Updater

HTML:
<div id="user-profile">
    <h2 id="profile-name">Loading...</h2>
    <p id="profile-bio"></p>
    <input type="text" id="name-input" placeholder="Enter name">
    <textarea id="bio-input" placeholder="Enter bio"></textarea>
    <button id="update-btn">Update Profile</button>
</div>
<div id="preview"></div>
JavaScript:
$(document).ready(function() {
    // Load initial data
    $("#profile-name").text("John Doe");
    $("#profile-bio").text("Web Developer");

    // Real-time preview
    $("#name-input, #bio-input").on("input", function() {
        var name = $("#name-input").val() || "Your Name";
        var bio = $("#bio-input").val() || "Your bio";

        var preview = "<h3>" + name + "</h3><p>" + bio + "</p>";
        $("#preview").html(preview);
    });

    // Update profile
    $("#update-btn").click(function() {
        var newName = $("#name-input").val();
        var newBio = $("#bio-input").val();

        if (newName.trim() !== "") {
            $("#profile-name").text(newName);
        }

        if (newBio.trim() !== "") {
            $("#profile-bio").text(newBio);
        }

        // Clear inputs
        $("#name-input, #bio-input").val("");
        $("#preview").html("<p style='color: green;'>Profile updated!</p>");

        setTimeout(function() {
            $("#preview").html("");
        }, 2000);
    });
});
Exercise:
  1. Create a simple blog post editor with a title input and content textarea
  2. Display a live preview of the post below the editor
  3. Add a "Publish" button that moves the content to a "published" section
  4. Use .text() for the title and .html() for the content (with proper escaping)
  5. Add a character counter for the title (max 100 characters)

Summary

  • .text() - Get/set text content (safe, escapes HTML)
  • .html() - Get/set HTML content (powerful, requires caution)
  • .val() - Get/set form element values
  • Getters return the first element, setters apply to all
  • Callback functions enable index-based and conditional updates
  • Always validate and sanitize user input for security

ES
Edrees Salih
17 hours ago

We are still cooking the magic in the way!