Introduction to jQuery
JQuery Syntax
JQuery Effects
JQuery HTML
JQuery Traversing
jQuery Set Methods, which are used to update or modify content, attributes, styles, and form values of elements dynamically.
We will use the same three methods from the previous page to set content:
Method |
Description |
Example Code |
---|---|---|
.text() |
Sets the plain text content of an element |
$("#element").text("New text"); |
.html() |
Sets the HTML content (with tags) |
$("#element").html("<b>Bold</b>"); |
.val() |
Sets the value of form fields |
$("#input").val("New value"); |
The following example demonstrates how to set content with the jQuery text()
, html()
, and val()
methods:
Try it yourself
In jQuery, the text()
, html()
, and val()
methods can also accept a callback function as an argument. This callback function allows you to dynamically set the value based on the current content of the element.
The following example demonstrates text(), val()
and html()
with a callback function:
Try it yourself
The .attr()
method in jQuery is used to set or get HTML attributes of elements like src
, href
, title
, id
, etc.
The following example demonstrates how to change (set) the value of the href attribute in a link:
Try it yourself
The attr()
method also allows you to set multiple attributes at the same time.
The following example demonstrates how to set both the href and title attributes at the same time:
Try it yourself
you can use a callback function with jQuery’s .attr()
method to dynamically set attribute values based on existing values or other logic.
$(selector).attr("attributeName", function(index, currentValue){ // return new value });
index
: The index of the element in the jQuery collection.currentValue
: The current value of the specified attribute.The following example demonstrates attr()
with a callback function:
Try it yourself