HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
We will use the same three methods from the previous page to set content
We will use the same three methods from the previous page to set content:
text()
- Sets or returns the text content of selected elementshtml()
- Sets or returns the content of selected elements (including HTML markup)val()
- Sets or returns the value of form fieldsThe following example demonstrates how to set content with the jQuery text()
, html()
,
and val()
methods:
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
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:
$("#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 + ")";
});
});
The jQuery attr()
method is also used to set/change attribute values.
The following example demonstrates how to change (set) the value of the href attribute in a link:
$("button").click(function(){
$("#w3s").attr("href", "/jquery/");
});
The attr()
method also allows you to set multiple attributes at the same
time.
The following example demonstrates how to set both the href and title attributes at the same time:
$("button").click(function(){
$("#w3s").attr({
"href" : "/jquery/",
"title" : "w3resource jQuery Tutorial"
});
});
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:
$("button").click(function(){
$("#w3s").attr("href", function(i, origValue){
return origValue + "/jquery/";
});
});
Use a jQuery method to change the text of a <div> element to "Hello World".
$("div").("");
For a complete overview of all jQuery HTML methods, please go to our jQuery HTML/CSS Reference.