jQuery - Set Content and Attributes


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

We will use the same three methods from the previous page 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 illustrates how to set content with jQuery 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");
});

A Callback Function for text(), html(), and val()

All three jQuery modes above: text (), html (), and val (), also come with a re-drive function. The back drive function has two components: the current element index in the selected items list and the actual (old) value. Then return the character unit you wish to use as the new value from the function.

The following example illustrates text() and html() with a callback function:


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


Set Attributes - attr()

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

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


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

The attr() method allows you to set multiple attributes at once.

The following example shows how to set both href and title attributes simultaneously:


Example
$("button").click(function(){
  $("#w3s").attr({
    "href" : "https://www.w3schools.com/jquery/",
    "title" : "W3Schools jQuery Tutorial"
  });
});


A Callback Function for attr()

The jQuery method attr(), also comes with a re-drive function. The callback function has two components: the current element index in the list of selected elements and the actual (old) value. Then return the character unit you wish to use as the new attribute value from the function.

The following example illustrates attr() with a duplicate drive function:


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