jQuery set content and properties

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

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

  • text() - Set or return the text content of the selected element
  • html() - Set or return the content of the selected element (including HTML tags)
  • val() - Set or return the value of the form field

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("Dolly Duck");
});

Try It Yourself

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

The three jQuery methods: text(), html(), and val() also have callback functions. The callback function takes two parameters: the index of the current element in the selected element list, and the original (old) value. Then return the string you want to use as the new value of the function.

The following example demonstrates the 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 Attribute - attr()

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

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

Example

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

Try It Yourself

The attr() method also allows you to set multiple attributes simultaneously.

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

Example

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

Try It Yourself

attr() Callback Function

The jQuery attr() method also provides a callback function. The callback function takes two parameters: the index of the current element in the selected element list, and the original (old) value. Then it returns the string you want to use as the new value in the function.

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

Example

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

Try It Yourself

jQuery HTML Reference Manual

For the complete content of jQuery HTML methods, please visit the following reference manual: