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.
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))
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>
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!’.
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: