jQuery - Setting Content and Attributes
Setting Content - text(), html(), and val()
We will use the same three methods from the previous chapter to set content:
- text() - Sets or returns the text content of selected elements
- html() - Sets or returns the content of selected elements (including HTML markup)
- val() - Sets or returns the value of form fields
The following example demonstrates how to set content using the text(), html(), and val() methods:
Example
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("tutorialpro");
});
Callback Functions for text(), html(), and val()
The three jQuery methods: text(), html(), and val(), also have callback functions. The callback function has two parameters: the index of the current element in the list of selected elements, and the original (old) value. You then return the new value you want to use.
The following example demonstrates text() and html() with callback functions:
Example
$("#btn1").click(function(){
$("#test1").text(function(i, origText){
return "Old text: " + origText + " New text: Hello world! (index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i, origText){
return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")";
});
});
Setting Attributes - attr()
The jQuery attr() method is also used to set/change attribute values.
The following example demonstrates how to change (set) the href attribute value in a link:
Example
$("button").click(function(){
$("#tutorialpro").attr("href", "http://www.tutorialpro.org/jquery");
});
The attr() method also allows you to set multiple attributes at once.
The following example demonstrates how to set both href and title attributes:
Example
$("button").click(function(){
$("#tutorialpro").attr({
"href" : "http://www.tutorialpro.org/jquery",
"title" : "jQuery Tutorial"
});
});
Callback Function for attr()
The jQuery method attr() also provides a callback function. The callback function has two parameters: the index of the current element in the list of selected elements, and the original (old) value. You then return the new value you want to use.
The following example demonstrates the attr() method with a callback function:
Example
$("button").click(function(){
$("#tutorialpro").attr("href", function(i, origValue){
return origValue + "/jquery";
});
});