사용자 도구

사이트 도구


wiki:javascript:jquery:jquery_note:jquery_references_html_css:jquery_text_method

jQuery text() Method

  • description : jQuery text() Method
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-06-02


The source of this article

Example

모든 <p> 요소들의 텍스트 내용을 설정합니다.

<body>
 
  <button>Set text content for all p elements</button>
 
  <p>This is a paragraph.</p> <!-- 버튼 클릭 시 Hello World로 겹쳐 쓴다. -->
  <p>This is another paragraph.</p> <!-- 버튼 클릭 시 Hello World로 겹쳐 쓴다. -->
 
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        $("p").text("Hello World");
      });
    });
  </script>
 
</body>

Definition and Usage

text() 메서드는 선택한 요소의 텍스트 내용을 설정(set)하거나 반환(return)합니다.

이 메서드를 사용하여 콘텐츠를 반환(return)하면, 일치하는 모든 요소의 텍스트 내용을 반환합니다(HTML markup 이 제거됨).

이 메서드를 사용하여 콘텐츠를 설정(set)하면, 일치하는 모든 요소의 내용을 겹쳐 씁니다.

Tip: 선택한 요소의 innerHTML (text + HTML markup)을 설정하거나 반환하려면, html() 메서드를 사용합니다.

Syntax

선택자의 텍스트 내용을 가져와 반환(표시)합니다:

$(selector).text( )


텍스트 내용을 설정합니다(선택자의 요소에 content를 겹쳐 씁니다):

$(selector).text(content)


함수를 사용하여 텍스트 내용을 설정합니다(겹쳐 씁니다):

$(selector).text(function(index,currentcontent))


Parameter Description
content 필수입니다. 선택한 요소에 대한 새로운 텍스트 내용을 지정합니다.
Note: 특수 문자가 인코딩됩니다.
function(index,currentcontent) 선택사항, 선택한 요소에 대해 새로운 텍스트 내용을 반환하는 함수를 지정합니다.
index - 세트(set) 내부 요소의 인덱스 위치를 반환합니다.
currentcontent - 선택한 요소들의 현재 내용을 반환합니다.

Example

선택한 요소의 텍스트 내용을 반환합니다(가져와서 표시합니다):

<body>
 
  <button>Return the text content of all p elements</button>
 
  <p>This is a paragraph.</p>
  <p>This is <b>another</b> paragraph.</p>
 
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        alert($("p").text());
        // 두 개의 p요소를 브라우저의 알림(alert)창에 표시합니다.
      });
    });
  </script>
 
</body>


Example

함수를 사용하여 선택한 요소들의 텍스트 내용을 설정합니다(겹쳐 씁니다)

<body>
 
<button>Set text content of the p elements</button>
 
<p>This is a paragraph.</p> <!-- This p element has index: 0 -->
<p>This is another paragraph.</p> <!-- This p element has index: 1 -->
 
<script>
  $(document).ready(function(){
    $("button").click(function() {
      $("p").text(function(n){
        return "This p element has index: " + n;
      });
    });
  });
</script>
</body>
/var/services/web/dokuwiki/data/pages/wiki/javascript/jquery/jquery_note/jquery_references_html_css/jquery_text_method.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)