In the previous tutorial, we had a discussion about JQuery get attributes, which were help full to get the values associated with the elements in DOM. In this tutorials, we are going to discuss about how to use JQuery Set Attributes.

jQuery Set Attributes :

JQuery Set Attributes are similar like get attributes. But in this case by using set attributes, we can set or update the values of html elements in DOM.

  • text()
  • html()
  • val() and
  • attr()

jQuery Set Attributes text() :

This text() method is used to set the text content to DOM element.

$("p").click(function() {
            $("#target").text("Sample String");

<p id="target">Please change my text !</p>


On the above example, by using the ID selector we have changed the text value of <p> element.

We can also use the callback functions in JQuery Set attributes like below :

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

<p id="test1">Please change my text !</p>

<input type="button" id="btn"/>


On the above example, by clicking on the button text method will get the originalText from <p> and append the new text to old text.

jQuery Set Attributes html() :

This html() method is used to set the html content to DOM element.

$("p").click(function() {
            $("#target").html("<b>Sample String</b>");

<p id="target">Please add HTML Content</p>


On the above example, by using the ID selector we have changed the text value of <p> element.

jQuery Set Attributes val() :

This val() method is used to set the value to input elements of DOM.

$("p").click(function() {
            $("#target").val("Enter Username Here");

<input type="text" id="target"/>


jQuery Set Attributes attr() :

It is used to set one or more attributes to selected set of elements. Example, Alt and title are the two attributes on the jQuery. We can add the title attribute and change the alt attribute at the same time.

$("#btn").click(function() {
            $("#target").attr("value","Enter Username Here");

<input type="text" id="target"/>


By using the above JQuery Set attribute methods, we can manipulate the DOM elements easily.

Happy Learning 🙂

About the Author:

Founder of Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment