jQuery - Set Content and Attributes


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

On the next page, we'll employ the identical three approaches we used previously to adjust the 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

Here is an example that shows how you can put text, HTML, and values using jQuery's 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 »

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

The three jQuery methods, text(), html(), and val(), each include a feature known as a callback function. This callback function has two pieces of information: the position of the current element in the list of selected elements and the original (old) value of the element. You can then use this function to specify the new value you want to assign to the element.

In this example, we showcase the usage of the text() and html() functions along 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 + ")";
  });
});
Try it Yourself »

Set Attributes - attr()

You can use the jQuery method called attr() to change or set attribute values.

This example shows how to modify the URL address in a hyperlink by adjusting the 'href' attribute.

Example

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

The attr() method lets you change more than one thing about something all at once.

Here's an example that shows how to simultaneously assign values to the 'href' and 'title' attributes:

Example

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

A Callback Function for attr()

The jQuery function called "attr()" has a special feature called a callback function. This callback function has two things inside it: the position of the current element in the list of selected elements, and the old attribute value. You can then create a new string in this function, and that string will become the new attribute value.

Here's an example of how to use the attr() function with a callback.

Example

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