jQuery - set()
Setting Values and Content in jQuery (Even Without .set())
You might think jQuery has a .set() method—but it doesn’t. Instead, jQuery uses specific methods to set different types of values, like:
-
Text
-
HTML
-
Input values
-
CSS properties
-
Attributes
Let’s go through the most common ones:
1. Set Text with .text()
This sets (or changes) the text inside an element.
$("#message").text("Hello, world!");
This replaces whatever text was in the element with ID message.
2. Set HTML with .html()
This sets the HTML content of an element (including tags).
$("#content").html("<strong>Bold text!</strong>");
It will show bold text inside the element.
3. Set Form Input Values with .val()
This sets the value of form fields like inputs or text boxes.
$("#nameInput").val("John Doe");
Now the input box with ID nameInput will be filled with "John Doe".
4. Set CSS with .css()
This changes one or more CSS styles on an element.
$("#box").css("background-color", "blue");
You can also set multiple properties at once:
$("#box").css({
width: "200px",
height: "100px"
});
5. Set Attributes with .attr()
This sets HTML attributes like href, src, alt, etc.
$("#link").attr("href", "https://example.com");
Now the link goes to the new URL.
Summary (without a table!):
-
Use .text() to set plain text.
-
Use .html() to set HTML content.
-
Use .val() to set values in form fields.
-
Use .css() to set styles.
-
Use .attr() to set attributes.
Final Thought:
Even though jQuery doesn’t have a .set() function, setting things is easy once you know which method fits what you’re changing. Each method does a specific type of "setting" so your code stays clear and powerful.