jQuery text() Method
jQuery provide 3 methods to Set or Get the content from a DOM element i.e. text() , html() and val() . These three things might seem like the same thing, but they're not. When these methods are called with no argument, it is referred to as a getters, because it reads (or get) the value of the element. When these methods are called with a value as an argument, it's referred to as a setter because it assign (or sets) that value. text() - The jQuery text() method is used to set or return the text content of the selected elements. This method gets the combined text contents of all matched elements . The text() method also return the text content of child elements.Set Contents with text() Method
$("#btn").click(function(){
$("#pr").text("Paragrapg changed using text() method");
});
<p id="pr">Changing this text to...</p>
<button id="btn">Set Values</button>
Get Contents with text() Method
$("#btn").click(function(){
var str = $("#pr").text();
alert(str);
});
<p id="pr">Changing this text to...</p>
<button id="btn">Get Values</button>

Changing this text to...
<html>
<head>
<title>jQuery text() example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btnGet").click(function(){
var str = $("#pr").text();
alert(str);
});
$("#btnSet").click(function(){
$("#pr").text("Paragraph changed using text() method");
});
});
</script>
</head>
<body>
<p id="pr">Changing this text to...</p>
<button id="btnGet">Get Values</button>
<button id="btnSet">Set Values</button>
</body>
</html>
Difference between val() and text()
jQuery .val() method gets the value of the input element, regardless of type while jQuery .text() gets the innerText (not HTML) of all the matched elements. It is important to note that the .text() will not work on input elements.
Related Topics