text()/html()

html() 메서드는 선택한 요소의 하위 요소를 가져와 문자열로 반환하거나 하위 요소를 전부 제거하고 새 요소를 바꿀 때 사용합니다. text() 메서드는 선택한 요소에 포함되어 있는 전체 텍스트를 가져오거나 선택한 하위 요소를 전부 제거하고 새 텍스트를 생성할 때 사용합니다.

$("선택자").text(); $("선택자").text("변경할 요소") $("선택자").html(); $("선택자").html("변경할 요소");

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jquery08_textClass</title>
    <style>
        @font-face {
        font-family: 'ImcreSoojin';
        src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_20-04@2.3/ImcreSoojin.woff') format('woff');
        font-weight: normal;
        font-style: normal;
        }
        body {font-family: 'ImcreSoojin';}
        li.red {color: #c7254e; background-color: #f9f2f4; border: 1px dashed #a51a3d;}
    </style>
</head>
<body>

    <h1>탐색(Traversing)</h1>
    <ul>
        <li>addClass() 메서드는 선택한 요소에 클래스를 생성하고, removeClass() 메서드는 선택한 요소에서 지정한 클래스를 삭제합니다.</li>
        <li>toggleClass() 메서드는 선택한 요소에 지정한 클래스가 없으면 생성하고 있을 경우에는 삭제합니다.</li>
        <li>hasClass() 메서드는 선택한 요소에 지정한 클래스가 있으면 ture를 반환하고, 없으면 false를 반환합니다.</li>
    </ul>

    <button class="btn1">btn1</button>
    <button class="btn2">btn2</button>
    <button class="btn3">btn3</button>
    <button class="btn4">btn4</button>

<!-- script -->
<script src="jquery.min_1.12.4.js"></script>
<script>
    //세번째 li를 선택해서 글씨 색을 빨간색으로 변경(10)
    //$("li:eq(2)").css("backgroundColor","red");
    //$("li:gt(1)").css("backgroundColor","red");
    //$("li:last").css("backgroundColor","red");
    //$("li:contains('hasClass()')").css("backgroundColor","red");
    //$("li:last-child").css("backgroundColor","red");
    //$("li:last-of-type").css("backgroundColor","red");
    //$("li:nth-child(3)").css("backgroundColor","red");
    //$("li:nth-of-type(3)").css("backgroundColor","red");
    //$("li:nth-last-child(1)").css({color : "red"});
    //$("li:nth-last-of-type(1)").css({color : "red"});
    //$("li:last-child").css({color : "red"});
    //$("li:nth-child(3n)").css({color : "red"});
    //$("li:nth-child(2)~li").css({color : "red"});

    //버튼을 클릭하면 첫번째 li의 글씨를 경고창으로 표시해주세요
    $(".btn1").click(function(){
        let text = $("li:first").text();
        alert(text);
    });
    
    //버튼2를 클릭하면 마지막 li의 글씨를 변경하세요
    //text() 메서드는 선택한 요소에 포함되어 있는 전체 텍스트를 가져오거나 선택한 하위 요소를 전부 제거하고 새 텍스트를 생성할 때 사용합니다.
    $(".btn2").click(function(){
        $("li:eq(2)").text("text() 메서드는 선택한 요소에 포함되어 있는 전체 텍스트를 가져오거나 선택한 하위 요소를 전부 제거하고 새 텍스트를 생성할 때 사용합니다.");
    });

    $(".btn3").click(function(){
        $("li:eq(1)").html("<strong>addClass()</strong> 메서드는 선택한 요소에 클래스를 생성하고, removeClass() 메서드는 선택한 요소에서 지정한 클래스를 삭제합니다.")
    });

</script>
</body>
</html>

Last updated

Was this helpful?