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.
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
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.");
text() if you're displaying user-generated data to avoid security risks like XSS (Cross-Site Scripting).
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");
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"
});
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 + ")";
});
});