jQuery API

.text()

Contents:

.text() Returns: String

Description: Get the combined text contents of each element in the set of matched elements, including their descendants.

  • version added: 1.0.text()

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.) Consider the following HTML:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
  <ul>
  <li>list item 1</li>
  <li>list <strong>item</strong> 2</li>
  </ul>
  </div>

The code $('div.demo-container').text() would produce the following result:

Demonstration Box list item 1 list item 2

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

As of jQuery 1.4, the .text() method returns the value of text and CDATA nodes as well as element nodes.

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

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:blue; margin:8px; }
  b { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p><b>Test</b> Paragraph.</p>

  <p></p>
<script>
    var str = $("p:first").text();
    $("p:last").html(str);
</script>

</body>
</html>

Demo:

.text( textString ) Returns: jQuery

Description: Set the content of each element in the set of matched elements to the specified text.

  • version added: 1.0.text( textString )

    textStringA string of text to set as the content of each matched element.

  • version added: 1.4.text( function(index, text) )

    function(index, text)A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

Unlike the .html() method, .text() can be used in both XML and HTML documents.

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <). Consider the following HTML:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
  <ul>
    <li>list item 1</li>
    <li>list <strong>item</strong> 2</li>
  </ul>
</div>

The code $('div.demo-container').text('<p>This is a test.</p>'); will produce the following DOM output:

<div class="demo-container">
&lt;p&gt;This is a test.&lt;/p&gt;
</div>

It will appear on a rendered page as though the tags were exposed, like this:

<p>This is a test</p>

The .text() method cannot be used on input elements. For input field text, use the .val() method.

As of jQuery 1.4, the .text() method allows us to set the text content by passing in a function.

$('ul li').text(function(index) {
  return 'item number ' + (index + 1);
});

Given an unordered list with three <li> elements, this example will produce the following DOM output:

<ul>
  <li>item number 1</li>
  <li>item number 2</li>
  <li>item number 3</li>
</ul>

Example:

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

<!DOCTYPE html>
<html>
<head>
  <style>

  p { color:blue; margin:8px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Test Paragraph.</p>
<script>$("p").text("<b>Some</b> new text.");</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .text() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .text()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://twitter.com/andersmattson Anders Mattson

    This function seems to return different values for different browsers in some cases. IE7, for example strips out new lines and tabs in clean text content while Firefox (currently using 3.5.7) and Chrome doesn’t.One row    Another row with tab at the beginningreturns “One rowAnother row” in IE7.Can anyone confirm or deny this?

  • http://twitter.com/Haraldson Hein Haraldson Berg

    Should I be able to use .text() to correctly retrieve formatted text, e.g. text with brake or strong elements? In my case, I have a text formatted with a break element, and there are no spaces on neither side of the break. If I run .text() on the wrapping element, what I get is not what I expect—the two lines are joined with no space in between; ‘Line 1Line 2′. I assume there’s some use of regex here—could it be rewritten to fix this?

  • Mike

    Anders,

    Why do you care? Isn’t the whitespace irrelevent in html?
    What are you trying to do?

  • Anonymous

    I’ve found that too, and I think I found some solution to this.
    For example, you have jQuery object – div, named oDiv. You need to get it’s non-formatted text and insert it into textarea.

    var strText = $(”)
    .html(oDiv.html().replace(/BR/g, ‘{new_line}’))
    .text().replace(/{new_line}/g, ‘n’);

    // that “BR” is with lt and gt, i couldn’t get it to be this way in this comment :(

    What this code do, is replace br-s with some text, takes non-formatted text from that html and then replaces that text back to new lines. Minus is, that if you have string “{new_line}” somewhere in your html, it will be replaces to new line.. Of course, you can change it to somewhat more unlikely..

  • fidian

    I noticed the same problem with some text encoding that I was doing. This was not working in IE.

    encodedString = $(”).text(string).html();

    Luckily, if you use a pre tag, then IE preserves whitespace (at least in IE 8).

    encodedString = $(”).text(string).html();

  • Matt

    One quirk for anyone else experiencing this:

    $(“#myLabel”).text(“newText”);

    Will continue to append the string newText instead of replacing it. You need to specify the label as:

    Then it will correctly replace the text.

  • Adam

    As others have mentioned this function may or may not preserve whitespace and formatting characters (tabs, newlines etc.) from browser to browser. So far as my testing could tell Chrome, Firefox, Safari, Opera, Netscape, Flock, Minefield, K-Meleon, Epiphany, Konqueror, Shiretoko and SeaMonkey ALL preserve at least the newline characters. Internet Explorer was the only one I encountered that did not.

    This is particularly an issue if you are trying to run multiline regular expressions on the .text() content of an element. Personally my expressions were failing in all versions of IE and only IE. I tried changing the expressions, using various implementations of them… nada. I couldn't get my multiline regular expressions to match the start and end of lines at all. More confusingly my results for even the most simple expressions weren't matching those of any online regular expression testing tools. Anyway, point is that I have finally traced those problems back to this function removing formatting characters.

    Hope this saves some time for someone.

  • jmslouie

    My alternative way to retrieve text from my non-input element tags is to use .html() and replace
    tags using regular expression but I removed all the new line first so there will be no double new line on non-IE browsers

    $('#my_element').html().replace(/n/g, '').replace(/
    /ig, 'n');

  • Maxx

    Javascript is not HTML, and whitespace makes all the difference if you're trying to match whole word strings.

  • Maxx

    This is javascript, not HTML. Whitespace characters are still characters for any and all processing semantics.

  • Ccaro

    What if you only want to get the text of the selected element MINUS its descendants?
    For examples, This textlink and I only want it to return “This text”?

  • T63030

    $(document.createTextNode(123)).text(456).text();
    // still 123

  • http://pulse.yahoo.com/_D3EKNXCCNITKIVBRUONR23V4A4 Mike

    we had a problem where html entities coming from an ajax call and assigned to an input field were not being shown properly, we were able to fix this in this way:

    var sFromAjaxCall = stringFromAjax();
    var sParsed = (”).html(sFromAjaxCall).text();
    $(‘#inputField’).val(sParsed);

  • Alfonso de la Osa

    this.context.children should be this.context.childNodes, take care with the example, is not tested

  • Alfonso de la Osa

    Same doubt here. I really don’t recommend this but I don’t know a better practice, anyone please?
    $.fn.extend({
    immediateText: function() {
    return this.clone().find(“*”).remove().end().text();
    }
    });

  • http://crashplan.probackup.nl/ Pro Backup

    Goal is to generate a cross browser identical MD5 hash of a long text part of an UTF-8 encoded xhtml document. Therefore I started looking at the .text() method. Unlucky not all not md5 output values were identical. I think that is not the fault of jQuery, f.e. start copying and pasting text from different browsers into a text editor and they are all different.

    Solution in this case was to use the .html() method instead, replace all (tags|space characters) by a space, replace the double spaces by a single space, trim it, and finally hash it.

  • Pt

    x.contents().filter(function(){ return(this.nodeType == 3); }).text() seems to work for me

  • Pt

    x.contents().filter(function(){ return(this.nodeType == 3); }).text() seems to work for me

  • Micha

    I guess there is a little bug in .text() function. Can somebody else confirm this:

    $('<strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong').text();

    returns 'test is | not' instead of 'test is | not | wrong'

    But if you wrap the hole string first with an other tag it works.
    $('<span><strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong</span>').text();

    Greetings from Germany

  • Micha

    I guess there is a little bug in .text() function. Can somebody else confirm this:

    $('<strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong').text();

    returns 'test is | not' instead of 'test is | not | wrong'

    But if you wrap the hole string first with an other tag it works.
    $('<span><strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong</span>').text();

    Greetings from Germany

  • Micha

    I guess there is a little bug in .text() function. Can somebody else confirm this:

    $('<strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong').text();

    returns 'test is | not' instead of 'test is | not | wrong'

    But if you wrap the hole string first with an other tag it works.

    $('<span><strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong</span>').text();

    Greetings from Germany

  • Micha

    I guess there is a little bug in .text() function. Can somebody else confirm this:

    $('<strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong').text();

    returns 'test is | not' instead of 'test is | not | wrong'

    But if you wrap the hole string first with an other tag it works.

    $('<span><strong>test</strong> <br /><em>is</em> | <strong>not </strong> | wrong</span>').text();

    Greetings from Germany

  • http://twitter.com/SeanJA Sean Sandy, BCS

    Yep, that is what I get in Firefox

  • vitoma

    “Get the combined text contents of each element in the set of matched elements”

    In the first example, ' | wrong' is not contained with in an element, where as in the second example, it is contained within an element.

  • http://twitter.com/thefooshshow Richard Fouchaux

    I'm having a problem due to the.createTextNode() auto-escaping… I need to replace English with French… the charset is declared as utf-8 but if I pass the French strings as translated I get ? s and other replacement characters. If I convert them to entities it escapes the ampersand. Anyone ever encounter this? Is there a workaround?