Setting Content: text(), html(), val() Methods
In this tutorial, we will have a look at jQuery's mostly used methods for setting content: .text()
, .html()
and .val()
methods.
The .text()
function sets the text contents of all matched elements. The .html()
function also sets the HTML contents of the each element of all the matched elements.
Consider the HTML document below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Title of this Page</title>
</head>
<body>
<p>A paragraph.</p>
<p>Followed by another paragraph.</p>
<div>A div element.</div>
<div>Followed by another div element.</div>
</body>
</html>
On adding the following jQuery code into it
<script type="text/javascript">
$(document).ready(function(){
$("p").text("Some text inside a paragraph");
$("div").html("<b>Content inside div elements in bold</b>");
});
</script>
$("p").text("Some text inside a paragraph")
replaces the existing text contents of all paragraph elements with the text Some text inside a paragraph
. And $("div").html("<b>Content inside div elements in bold</b>")
matches all div elements and replaces their HTML contents with <b>Content inside div elements in bold</b>
.
The .val()
method is generally used to set the values of form elements like <input/>
, <select/>
and <textarea/>
. Consider the below HTML, where we have the <input/>
, <select/>
and <textarea/>
elements with their values set to nothing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Title of this Page</title>
</head>
<body>
<form action="">
<input type="text"/>
<select>
<option value="">SELECT</option>
<option value="r2d2">R2-D2</option>
<option value="c3po">C-3PO</option>
<option value="bb8">BB-8</option>
</select>
<textarea rows="2" cols="27"></textarea>
</form>
</body>
</html>
If you try to retrieve the values from the form elements with $("input").val()
, $("select").val()
and $("textarea").val()
, they will return empty strings. You can set their values by passing a desired value as an argument to each of the respective .val()
method.
<script type="text/javascript">
$(document).ready(function(){
$("input").val('ScriptVerse');
$("select").val('c3po');
$("textarea").val('Textarea has a new text.');
});
</script>