Set Content - Text, HTML, and Val : Example
Set Content - Text, HTML, and Val : Example
We will use the same three methods from the previous page to set content:
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("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
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 <b>world!</b>
(index: " + i + ")";
});
});
The following example demonstrates how to change (set) the value of the href attribute in a link:
Example
$("button").click(function(){
$("#w3s").attr("href", "https://www.w3schools.com/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:
Example
$("button").click(function(){
$("#w3s").attr({
"href" : "https://www.w3schools.com/jquery/",
"title" : "W3Schools jQuery Tutorial"
});
});
Example
$("button").click(function(){
$("#w3s").attr("href", function(i, origValue){
return origValue + "/jquery/";
});
});