HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Get and Set

Dom manipulation is one of jQuery's strongest areas. It provides incredibly simple methods to "get" (retrieve) or "set" (change) the content and attributes of HTML elements. Whether you're updating a title, reading a user's input, or changing an image source, these are the methods you'll use.


Content Methods Cheat Sheet

There are three primary methods for manipulating content. Each has a "get" mode and a "set" mode.

text() Plain Text
html() HTML Content
val() Form Values
attr() Attributes

1. text() and html()

Use text() to work with pure text content, and html() when you need to include HTML tags like <b> or <span>.

// GETTING content
var currentText = $("#myP").text(); 
var currentHTML = $("#myDiv").html();

// SETTING content
$("#myP").text("Hello World!"); 
$("#myDiv").html("<strong>Success!</strong> Content updated.");
Safety Note: Always prefer text() if you're displaying user-generated data to avoid security risks like XSS (Cross-Site Scripting).

2. val() — Working with Forms

The val() method is specifically designed for form elements like <input>, <select>, and <textarea>.

// GET value from an input field
var name = $("#nameInput").val();

// SET value of an input field
$("#nameInput").val("New User Name");

3. attr() — Manipulating Attributes

The attr() method allows you to read or change any attribute of an element, such as href, src, title, or alt.

// GET an attribute
var link = $("a").attr("href");

// SET an attribute
$("a").attr("href", "https://redohub.com");

// SET multiple attributes at once using an object
$("img").attr({
    "src": "logo.png",
    "alt": "Official Logo",
    "title": "RedoHub"
});

Using Callback Functions for Setting

All four methods (text, html, val, attr) also accept a callback function. This allows you to update content based on its current value.

// The callback receives the index and the OLD value
$("#btn").click(function() {
    $("#test2").html(function(i, oldText) {
        return "Old HTML was: " + oldText + " (Index: " + i + ")";
    });
});
Pro Tip: Most of these methods support **chaining**. You can set an attribute and then immediately start an animation on the same line!

Key Points to Remember

  • text() — Get or set plain text (safe).
  • html() — Get or set content including HTML tags.
  • val() — Specifically for form elements.
  • attr() — For everything else (src, href, title, etc.).
  • Methods with empty parentheses get values; methods with arguments set values.