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

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

$(selector).text()

2. For Setting Text

$(selector).text("Welcome all.")

3. For Setting Text through a Function

$(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.
Related: Developers should also know the related method which is the jQuery val method.

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.

<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.

<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.

<div id="div3">Welcome all!</div>
<button id="button3">Get Text</button>
 
$("#button3").click(function (e) {
    alert($("#div3").text());
}); 

The link to download the source code:

DOWNLOAD

Next tutorial – jQuery on Method Complete Usage Guide with Codes

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate