WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

jQuery - Set Content and Attributes

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

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

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

The following example shows 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 »

Text (), html (), and val () callback functions

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

The following examples demonstrate text () and html () with callback functions:

Example

$("#btn1").click(function(){
    $("#test1").text(function(i, origText){
        return "Old content: " + origText + " New content: Hello world!
        (record: " + I + ")";
    });
});

$("#btn2").click(function(){
    $("#test2").html(function(i, origText){
        return "Old html: " + origText + " New html: Hello <b>world!</b>
        (record: " + I + ")";
    });
});
Try it Yourself »

Set Attributes - attr()

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

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

Example

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

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

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

Example

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

A Callback Function for attr()

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 with the new value of 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

For a total review of all jQuery HTML strategies, it would be ideal if you go to our jQuery HTML/CSS Reference.