jQuery Set Content and Attributes
The methods from the previous lesson become setters when you pass a value. Unlike getters, setters change every matched element and return the jQuery object, so you can keep chaining.
Setting text, HTML and values
| Setter | Effect |
|---|---|
.text("…") |
Replaces the content with plain text (HTML is escaped, not parsed) |
.html("…") |
Replaces the content with parsed HTML |
.val("…") |
Sets the value of form fields |
.attr("name", "value") |
Sets an attribute |
.prop("name", value) |
Sets a DOM property (checked, disabled, …) |
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
<p id="t">original text</p>
<p id="h">original html</p>
<input id="v" value="original value">
<br><br>
<button id="set">Set all three</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#set").on("click", function () {
$("#t").text("Plain <b>text</b> — tags shown literally");
$("#h").html("Real <b>HTML</b> — <i>tags are parsed</i>");
$("#v").val("Hello from jQuery");
console.log("new value:", $("#v").val());
});
</script>
</body>
</html>Note: Never pass user input to
.html(). If someone types<img src=x onerror="…">,.html()would run their code (an XSS attack). Use.text()for anything that came from a user or a server.
Setting attributes
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
a { display: inline-block; margin: 6px 0; }
</style>
</head>
<body>
<a id="docs" href="https://jquery.com">jQuery site</a>
<br>
<button id="change">Point to the API docs</button>
<button id="multi">Set several attributes</button>
<button id="remove">Remove title</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#change").on("click", function () {
$("#docs").attr("href", "https://api.jquery.com").text("jQuery API docs");
console.log("href is now", $("#docs").attr("href"));
});
$("#multi").on("click", function () {
$("#docs").attr({
target: "_blank",
rel: "noopener",
title: "Opens in a new tab"
});
console.log("title:", $("#docs").attr("title"), "| target:", $("#docs").attr("target"));
});
$("#remove").on("click", function () {
$("#docs").removeAttr("title");
console.log("title after removeAttr:", $("#docs").attr("title"));
});
</script>
</body>
</html>Passing an object sets many attributes in one call. .removeAttr(name) deletes one.
Setting properties
Use .prop() for boolean state. To disable a button, set the property to true, and set it back to false to enable it:
$("#submit").prop("disabled", true); // disable
$("#submit").prop("disabled", false); // enable
$("input:checkbox").prop("checked", true); // tick every checkboxSetter callbacks: computing new values from old ones
Every setter also accepts a function. jQuery calls it once per element with the element's index and its current value, and uses the return value as the new value. This lets you update many elements differently in one call.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
li { margin: 3px 0; }
</style>
</head>
<body>
<ul id="prices">
<li data-base="10">Notebook: $10.00</li>
<li data-base="25">Backpack: $25.00</li>
<li data-base="4.5">Pen: $4.50</li>
</ul>
<button id="sale">Apply 20% off</button>
<button id="number">Number the items</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#sale").on("click", function () {
$("#prices li").text(function (i, oldText) {
const name = oldText.split(":")[0].replace(/^\d+\.\s/, "");
const price = $(this).data("base") * 0.8;
return name + ": quot; + price.toFixed(2) + " (sale)";
});
});
$("#number").on("click", function () {
$("#prices li").text(function (i, oldText) {
return (i + 1) + ". " + oldText.replace(/^\d+\.\s/, "");
});
console.log("items:", $("#prices li").map((i, el) => $(el).text()).get());
});
</script>
</body>
</html>| Setter with a function | Function receives |
|---|---|
.text(fn) / .html(fn) |
(index, oldText / oldHtml) |
.val(fn) |
(index, oldValue) |
.attr(name, fn) |
(index, oldAttrValue) |
.css(name, fn) |
(index, oldCssValue) |
Storing data
.data(key, value) stores any JavaScript value on an element — objects, arrays, even functions. It does not change the HTML attribute; it lives in jQuery's internal data store:
$("#cart").data("items", [{ id: 1, qty: 2 }]);
$("#cart").data("items").length; // 1
$("#cart").attr("data-items"); // undefined — the markup is unchanged
$("#cart").removeData("items");Use .attr("data-x", "…") when CSS selectors such as [data-x] must see the change, and .data() when you only need to keep state for your script.
Test yourself
Which setter is safe for displaying a name the user typed?
.html(name).text(name).append(name).attr("innerHTML", name)
How do you disable a button with jQuery?
$("#b").attr("disabled")$("#b").prop("disabled", true)$("#b").val("disabled")$("#b").disabled()
In $("li").text(function (i, old) { … }), what is i?
- The element
- The element's index in the set
- The old text
- The number of elements