jQuery Set

jQuery Set Content and Attributes

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.


Setting Content: text(), html(), and val()

To set content, simply place the new string inside the method's parameters.

Set Content Examples:

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

Callback Function Example:

$("#btn1").click(function(){
  $("#test1").text(function(i, origText){
    return "Old text: " + origText + " New text: Hello World! (index: " + i + ")";
  });
});

Setting Attributes: attr()

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.

Set Attribute Example:

$("button").click(function(){
  $("#w3s").attr("href", "https://intricatedevo.com");
  $("#w3s").text("IntricateDevo");
});

Setting Multiple Attributes

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.

Multiple Attributes Example:

$("button").click(function(){
  $("#w3s").attr({
    "href" : "https://intricatedevo.com",
    "title" : "IntricateDevo Tutorial"
  });
});

Exercise 1 of 1

?

Which syntax is correct for changing the src attribute of an image?