Latest web development tutorials

jQuery set the content and properties

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

We will use the same method as in the previous chapter set three elements:

  • text () - Sets or returns the text content of the selected element
  • html () - Sets or returns the contents of the selected element (including HTML tags)
  • val () - Returns the value or form fields

The following example demonstrates how text (), html () and val () method to set the content:

Examples

$ ( "# Btn1"). Click (function () {
$ ( "# Test1") text ( "Hello world!").;
});
$ ( "# Btn2"). Click (function () {
$ ( "# Test2") html ( "<b> Hello world </ b>!").;
});
$ ( "# Btn3"). Click (function () {
$ ( "# Test3") val ( "w3big").;
});

try it"


text (), html () and val () callback function

The above three jQuery methods: text (), html () and val (), also has a callback function. Callback by two parameters: the selected element in the list of elements under the current standard, as well as the original (old) value. Then the function returns the value you want to use the new string.

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

Examples

$ ( "# 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"


Set attributes - attr ()

jQuery attr () method is used to set / change the property value.

The following example shows how to change the value (setting) link href attribute:

Examples

$ ( "Button"). Click (function () {
$ ( "# W3big") .attr ( "href", "http://www.w3big.com/jquery");
});

try it"

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

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

Examples

$ ( "Button"). Click (function () {
$ ( "# W3big"). Attr ({
"Href": "http://www.w3big.com/jquery",
"Title": "jQuery Tutorial"
});
});

try it"


attr () callback function

Method jQuery attr (), also provide a callback function. Callback by two parameters: the selected element in the list of elements under the current standard, as well as the original (old) value. Then the function returns the value you want to use the new string.

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

Examples

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

try it"