jQuery text() Method
You are Here:
jQuery text() Method
The jQuery text()
method gets or sets the text content (innerText) of the selected elements.
The following points to be considered when using the jQuery text()
method
- When this method is used to get content, it gets the text content of all matched element.
- When this method is used to set content, it will overwrite all matched elements.
Note: Unlike the html() method, text() can be used in both XML and HTML documents.
In the following example, we will get the text content inside the <div>
tag.
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery text() Method</h1>
<div>
<p>Click on the button and check your console.</p>
<button>Click Me</button>
</div>
<script>
$(document).ready(function(){
$("button").click(function(){
console.log($("div").text());
});
});
</script>
</body>
</html>
Syntax
// Get content
$(selector).text();
// Set content
$(selector).text(text);
// Set content using a function
$(selector).text(func)
Parameter Values
Value | Explanation |
---|---|
text | Specifies a text to set as the content of each matched element. |
func | Specifies a function returning the text content to set. |
Set Text Content
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery text() Method</h1>
<button>Click Me</button>
<p></p>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("This is <strong>Paragraph</strong>");
});
});
</script>
</body>
</html>
Set Text Content using Function
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery text() Method</h1>
<button>Click Me</button>
<p></p>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text(function(){
var txt = "This is <strong>Paragraph</strong>";
return txt;
});
});
});
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in jQuery.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.