Just as you can read content using jQuery, you can also write new content to the DOM.
We use the exact same methods we learned in the previous chapter, but this time we pass a value into the parentheses.
To set content, simply place the new string inside the method's parameters.
text("new text") sets plain text.html("<p>new</p>") processes string as HTML markup.val("John") sets the input field value.
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("Hello world!");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
All three of the jQuery methods above also come with a powerful callback function.
The callback function takes two parameters: the current index of the element, and the original value.
You then return the new string you wish to use as the replacement.
$("#btn1").click(function(){
$("#test1").text(function(i, origText){
return "Old text: " + origText + " New text: Hello World! (index: " + i + ")";
});
});
The jQuery attr() method is also used to set or change attribute values.
You specify the attribute name, followed by a comma, and then the new value.
$("button").click(function(){
$("#w3s").attr("href", "https://intricatedevo.com");
$("#w3s").text("IntricateDevo");
});
The attr() method allows you to set multiple attributes at the same time.
You do this by passing a JavaScript object containing key-value pairs.
$("button").click(function(){
$("#w3s").attr({
"href" : "https://intricatedevo.com",
"title" : "IntricateDevo Tutorial"
});
});
Which syntax is correct for changing the src attribute of an image?