jQuery Set


In this tutorial, we will introduce you to various jQuery Set methods. The jQuery Set methods used to set the element content and attribute value.

The following are some of these methods: text(), html(), attr() and val().

jQuery text() Method

The jQuery text() methods used to set the element’s text content.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").text("This is text");
  });
});
</script>
</head>
<body>
 <p>This is paragraph tag.</p>
  <button>Click here</button>
</body>
</html>

jQuery html() Method

The jQuery html() methods used to set the html content.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#data").html("<b>This is a bold tag</b>");
  });
});
</script>
</head>
<body>
 <p id="data">This is paragraph tag.</p>
  <button>Click here</button>
</body>
</html>

jQuery attr() Method

The jQuery attr() methods used to set the value of an element’s attribute.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").attr("id","test"); 
  });
});
</script>
</head>
<body>
 <p id="data">This is paragraph tag.</p>
  <button>Click here</button>
</body>
</html>

jQuery val() Method

The jQuery val() methods used to set the value of form fields.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#username").val("admin");
  });
});
</script>
</head>
<body>
 <input type="text" name="username" id="username" value="username"/>
  <button>Click here</button>
</body>
</html>