← Back to Chapters

jQuery Set Methods

? jQuery Set Methods

? Quick Overview

The Set methods in jQuery allow you to modify content, text, attributes, and form values of elements dynamically after the page has loaded.

? Key Concepts

  • .html() – Set inner HTML
  • .text() – Set plain text
  • .attr() – Set attribute values
  • .val() – Set form input values

? Syntax / Theory

jQuery Set methods overwrite the existing content or value of selected elements.

  • $(selector).html("content")
  • $(selector).text("text")
  • $(selector).attr("name","value")
  • $(selector).val("value")

? Code Examples

? View Code Example
// Set HTML content
$("#myBox").html("<b>Bold text</b>");

// Set plain text
$("#myBox").text("Just plain text");

// Set an attribute value
$("a").attr("href","https://google.com");

// Set input field value
$("#myInput").val("New input value");

? Live Demo

Initial Content



Visit Link

? View jQuery Logic
// Run after DOM is ready
$(document).ready(function(){

// Set HTML content
$("#setHtml").click(function(){
$("#myBox").html("<i>Italic content set using .html()</i>");
});

// Set plain text
$("#setText").click(function(){
$("#myBox").text("<b>This will show as plain text</b>");
});

// Change link attribute and text
$("#setAttr").click(function(){
$("#myLink").attr("href","https://openai.com").text("Go to OpenAI");
});

// Update input value
$("#setVal").click(function(){
$("#myInput").val("Updated with .val()");
});

});

? Use Cases

  • Updating UI content dynamically
  • Prefilling form fields
  • Changing links, images, or attributes
  • Building interactive dashboards

✅ Tips & Best Practices

  • Use .text() when displaying user input for safety
  • Use .html() only with trusted content
  • .val() works only on form elements
  • .attr() can accept an object for multiple attributes

? Try It Yourself

  • Set multiple attributes using an object
  • Copy input value and display it inside a div
  • Toggle content using .html() and .text()