HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

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 demonstrates how to set content with the jQuery text(), html(), and val() methods:

Example
                     $("#btn1").click(function(){
                     $("#test1").text("Hello world!");
                     });
                     $("#btn2").click(function(){
                     $("#test2").html("Hello world!");
                     });
                     $("#btn3").click(function(){
                     $("#test3").val("Dolly Duck");
                     });
              
A Callback Function for text(), html(), and val()

All of the three jQuery methods above: text(), html(), and val(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value. You then return the string you wish to use as the new value from the function. The following example demonstrates 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 world!
              (index: " + i + ")";
               });
               });  
                  
              

A Callback Function for attr()

The jQuery method attr(), also comes with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) attribute value. You then return the string you wish to use as the new attribute value from the function. The following example demonstrates attr() with a callback function:

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