jQuery Set
jQuery - Setting Content and Attributes
Section titled “jQuery - Setting Content and Attributes”Learn how to dynamically modify the content and attributes of HTML elements using jQuery’s powerful manipulation methods.
Setting Content: text(), html(), and val()
Section titled “Setting Content: text(), html(), and val()”These three methods allow you to change the content inside selected elements or the value of form fields:
- text(content): Sets the text content of selected elements. Any existing content (including HTML markup) is replaced. HTML tags in the
contentstring are treated as literal text. - html(content): Sets the HTML content of selected elements. Any existing content is replaced. HTML tags in the
contentstring are parsed and rendered by the browser. - val(value): Sets the value of form fields like
<input>,<select>, and<textarea>.
Example: Setting content using each method:
// Assumes HTML like:// <p id="para1">Original text.</p>// <div id="div1">Original <em>HTML</em> content.</div>// <input type="text" id="input1" value="Original value">
$("#btnSetText").click(function() { $("#para1").text("This is the new plain text.");});
$("#btnSetHtml").click(function() { $("#div1").html("This is the **new HTML** content.");});
$("#btnSetValue").click(function() { $("#input1").val("New input value");});Practical Use Cases: Updating status messages, dynamically loading article content, pre-filling form fields.
Callback Functions for text(), html(), and val()
Section titled “Callback Functions for text(), html(), and val()”All three methods accept an optional callback function to determine the new content/value dynamically. This function is executed for each selected element.
The callback function receives two arguments:
- index: The index position of the element in the set of matched elements (starting at 0).
- currentValue: The original text content, HTML content, or value of the element before the change.
The function should return the new string value to be set for the current element.
Example: Using callbacks to prepend original content:
// Assumes HTML like:// <p id="p1">First paragraph.</p>// <p id="p2">Second paragraph.</p>// <div id="d1">Some <i>HTML</i>.</div>
$("#btnModifyText").click(function() { $("#p1, #p2").text(function(index, originalText) { return `Paragraph ${index + 1} (Original: ${originalText}) - Updated!`; });});
$("#btnModifyHtml").click(function() { $("#d1").html(function(index, originalHtml) { return `Original HTML: ${originalHtml} <br> **Updated!**`; });});Setting Attributes: attr()
Section titled “Setting Attributes: attr()”The jQuery attr() method is used to set or change the value of HTML attributes.
Syntax:
- To set a single attribute:
.attr(attributeName, value) - To set multiple attributes:
.attr({ attribute1: value1, attribute2: value2, ... })
Example: Changing the href and title attributes of a link:
// Assumes HTML like: <a id="myLink" href="/old-path" title="Old Title">Visit Us</a>
$("#btnUpdateLink").click(function() { $("#myLink").attr("href", "https://www.example.com");});
$("#btnUpdateMultipleAttrs").click(function() { $("#myLink").attr({ "href": "https://www.new-example.com", "title": "Visit our New Site!", "target": "_blank" // Add a new attribute });});Attributes vs. Properties: attr() vs. prop()
Section titled “Attributes vs. Properties: attr() vs. prop()”It’s important to understand the difference between HTML attributes and DOM properties, especially for boolean attributes or form element states.
- Attributes: Defined by HTML markup (e.g.,
<input type="checkbox" checked="checked">).attr()primarily works with these. - Properties: Belong to the DOM object in JavaScript (e.g., the
checkedproperty of the checkbox input element).prop()works with these.
Best Practice:
- Use
prop()for boolean properties likechecked,selected,disabled,readOnly. Getting their state (true/false) or setting them. - Use
attr()for other attributes likeid,class,href,src,title,data-*attributes, especially when the initial value defined in HTML is needed.
Example: Setting the checked state of a checkbox:
// Assumes HTML like: <input type="checkbox" id="agreeCheckbox">
// Correct way using prop()$("#btnCheck").click(function() { $("#agreeCheckbox").prop("checked", true);});
$("#btnUncheck").click(function() { $("#agreeCheckbox").prop("checked", false);});
// Reading the stateif ($("#agreeCheckbox").prop("checked")) { console.log("Checkbox is checked");} else { console.log("Checkbox is not checked");}
// Using attr() for checked might not consistently reflect the current state// $("#agreeCheckbox").attr("checked", "checked"); // Less reliable for state changesCallback Function for attr()
Section titled “Callback Function for attr()”Similar to content-setting methods, attr() also accepts a callback function to determine the new attribute value.
The callback function receives two arguments:
- index: The index position of the element in the set.
- currentValue: The original value of the attribute.
It should return the new attribute value string.
Example: Appending to an existing href using a callback:
// Assumes HTML like: <a class="productLink" href="/products">...</a>
$("#btnAppendPath").click(function() { $(".productLink").attr("href", function(i, originalHref) { // Append a query string, ensuring it starts correctly const separator = originalHref.includes('?') ? '&' : '?'; return originalHref + separator + "source=campaign"; });});jQuery HTML/CSS Reference
Section titled “jQuery HTML/CSS Reference”For a complete overview of all jQuery methods for manipulating HTML content and attributes, visit the official jQuery Manipulation documentation.