← Back to Index

.text()

Get the combined text contents of each element in the set of matched elements or set the text contents of the matched elements.

Examples

1. Get Text

// <h1>Hello World</h1>
const title = $('h1').text();

Result

"Hello World"

2. Set Text (escaped)

$('h1').text('User input <script>');

Result

<h1>User input &lt;script&gt;</h1>

3. Set with Function

// <li>A</li>
$('li').text((index, text) => `${index}. ${text}`);

Result

<li>0. A</li>

Parameters

Parameter Type Description
content string | function The text to set, or a function that returns the text. Function receives (index, currentText).

Returns: A string for getter, or the original SR object for setter.