Skip to main content

jQuery .text() function

By Sam Deering

There are two versions of this jQuery text attribute: .text() and .text(val).

jQuery text() function

Syntax: .text()

Functionality: .text() gets all the combined text contents of all matched elements.

Browser Compatiablity: text() works in all browsers that we have tested on.

Basic Example:

Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).

jQuery text(val) function

Syntax: .text(val)

Functionality: .text(val) is similar to .html() but escapes HTML (replace “< ” and “>” with their HTML entities).

Browser Compatiablity: text(val) works in all browsers that we have tested on.

Basic Example:
Add text to the paragraph (notice the bold tag is escaped).

$("p").text("Some new text.");

Alternative to jQuery text() function

This is a jQuery function which can be used instead of jQuery’s .text() to preserves line-breaks.

   $.fn.innerText = function(msg) {
         if (msg) {
            if (document.body.innerText) {
               for (var i in this) {
                  this[i].innerText = msg;
            } else {
               for (var i in this) {
                  this[i].innerHTML.replace(/&lt;br&gt;/gi,"n").replace(/(&lt;([^&gt;]+)&gt;)/gi, "");
            return this;
         } else {
            if (document.body.innerText) {
               return this[0].innerText;
            } else {
               return this[0].innerHTML.replace(/&lt;br&gt;/gi,"n").replace(/(&lt;([^&gt;]+)&gt;)/gi, "");



Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

Integromat Tower Ad