jQuery 「text」要素にテキスト文字を設定する

条件にマッチしたすべての要素に、引数として与えた文字列を設定します。このメソッドはHTMLドキュメント、XMLドキュメント共に使用可能です。.html()メソッドと異なり、.text()メソッドでは、引数として与えた文字列がエスケープされます。例えば「<span>」は、「&lt;span&gt;」となります。なお、.text()はフォームのinput要素を設定することはできません。代わりに.val()メソッドを使用しましょう。jQuery1.4以降では、引数にクロージャを記述できますので、動的なHTML文字列の設定が可能になりました。

書式

$( 対象要素 ).text(テキスト文字列);
$( 対象要素 ).text(function(){ 処理… });
$('div').text('文字列をセットします。');
$('div').text(function(){
    return $(this).index()+'番目のdiv要素です。';
});

サンプル

ボタンクリックでtext()メソッドを実行

<body>
<style>
  .sticky {
    background: #aaa;
  }
  .stickies {
    background: #00ffff;
  }
</style>
  <div class="main">
    <div class="header">
      <h1>サンプル</h1>
    </div>
    <div class="content">
      <div class="sticky">
        <p>コロッケ定食</p>
        <fingure><img src="./images/112083_s.jpg" width="200px" height="100px"></fingure>
      </div>
      <div class="sticky">
        <p>オムライス</p>
        <fingure><img src="./images/2227584_s.jpg" width="200px" height="100px"></fingure>
      </div>
      <div class="sticky">
        <p>ホットドッグ</p>
        <fingure><img src="./images/1418030_s.jpg" width="200px" height="100px"></fingure>
      </div>
      <button class="button">テキストを書き換え</button>
    </div>
    <div class="footer">
      <hr>
      <p class="copyright">2024 xxx all rights reserved.</p>
    </div>
  </div>
  <script>
    $(document).ready(function(){
      $('.button').on('click',function(){
        $('.sticky:first p').text('コロッケ定食(期間限定)');
        $('.sticky:last p').text('ホットドッグ(販売終了)');
      });
    });
  </script>
</body>
実行結果
初期画面
実行結果
テキストを書き換えボタンをクリックした後