JavaScript - - By Sam Deering

jQuery .text() function

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

(function($){
   $.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(/<br>/gi,"n").replace(/(<([^>]+)>)/gi, "");
               }
            }
            return this;
         } else {
            if (document.body.innerText) {
               return this[0].innerText;
            } else {
               return this[0].innerHTML.replace(/<br>/gi,"n").replace(/(<([^>]+)>)/gi, "");
            }
         }
   };
})(jQuery);