ドキュメント

Attributes/text

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Attributes

text( )

Get the combined text contents of all matched elements.
The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents. Cannot be used on input elements. For input field text use the val attribute.
Examples:

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

    var str = $("p:first").text();
    $("p:last").html(str);

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    var str = $("p:first").text();
    $("p:last").html(str);

  });
  </script>
  <style>
  p { color:blue; margin:8px; }
  b { color:red; }
  </style>
</head>
<body>
  <p><b>Test</b> Paragraph.</p>
  <p></p>
</body>
</html>

NameType

text( val )

Set the text contents of all matched elements.
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities). Cannot be used on input elements. For input field text use the val attribute.
Arguments:
valString
The text value to set the contents of the element to.
Examples:

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

$("p").text("<b>Some</b> new text.");

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("p").text("<b>Some</b> new text.");
  });
  </script>
  <style>
  p { color:blue; margin:8px; }
  </style>
</head>
<body>
  <p>Test Paragraph.</p>
</body>
</html>

NameType