jQuery - Set Content and Attributes


Set Content - text(), html(), and val()

We will use the same three methods from the previous chapter to set content:

  • text() - Set or return the text content of selected elements
  • html() - Set or return the content of selected elements (including HTML markup)
  • val() - Set or return 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("EXAMPLE"); });

Try it yourself »


Callback functions for text(), html(), and val()

The three jQuery methods above: 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. Then you return the string you wish to use as the function's new value.

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 + ")"; }); });

Try it yourself »


Set Attributes - attr()

The jQuery attr() method is also used to set/change attribute values.

The following example demonstrates how to change (set) the value of the href attribute in a link:

Example

$("button").click(function(){ $("#example").attr("href","http://www.example.com/jquery"); });

Try it yourself »

The attr() method also allows you to set multiple attributes at the same time.

The following example demonstrates how to set the href and title attributes at the same time:

Example

$("button").click(function(){ $("#example").attr({ "href" : "http://www.example.com/jquery", "title" : "jQuery Tutorial" }); });

Try it yourself »


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 selected element list, and the original (old) value. Then return the string you wish to use as the function's new value.

The following example demonstrates the attr() method with a callback function:

Example

$("button").click(function(){ $("#example").attr("href", function(i,origValue){ return origValue + "/jquery"; }); });

Try it yourself »
Other extensions