HI WELCOME TO KANSIRIS

jQuery Text Method – .text() – Complete Usage Guide with Codes

The jQuery text method (.text()) is used to either return or set the text contents of the selected elements.
For Returning – It returns the first matched element’s text content.
For Setting – It sets the text contents of all matched elements.

jQuery Text Syntax

The .text() method has 3 syntax.
1. For Returning Text
1
$(selector).text()
2. For Setting Text
1
$(selector).text("Welcome all.")
3. For Setting Text through a Function
1
$(selector).text(function(index,currentvalue))
  • index: returns the index of the element in the set.
  • currentvalue: returns the ‘text’ content of the element in the set.
Let us see some jQuery .text() examples to understand it’s working.

jQuery Text Example 1: Set Text of a div

I have one div and a button. On the button click, the text of the div is set.
This code is shown below.
1
2
3
4
5
<div id="div1">Welcome</div>
<button id="button1">Set Text</button>
$("#button1").click(function (e) {
    $("#div1").text("Hi <button>New Button</button> <span style='color: Red'>created</span>");
});
Unlike the jQuery HTML Method, the above .text() method does not create the button and span elements. It will just add them as text.
The div will just show – Hi <button>New Button</button> <span style=’color: Red’>created</span>.

jQuery Text Example 2: Set text of div using function

This time my div has an initial text content as ‘Welcome’.
I will add some text with the function parameter.
1
2
3
4
5
6
7
8
<div id="div2">Welcome</div>
<button id="button2">Set Text</button>
$("#button2").click(function (e) {
    $("#div2").text(function (index, currentvalue) {
        return currentvalue + " coder!";
    });
});
Here the div will show – ‘Welcome coder!’.

jQuery Text Example 3: Get text of a div

The below code alert the text of the div when the button is clicked.
1
2
3
4
5
6
<div id="div3">Welcome all!</div>
<button id="button3">Get Text</button>
$("#button3").click(function (e) {
    alert($("#div3").text());
});