toggleClass()

toggleClass() 메서드는 선택한 요소에 지정한 클래스가 없으면 생성하고 있을 경우에는 삭제합니다.

$("선택자").toggleClass()("클래스 이름");

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jquery05_addClass</title>
</head>
<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>
<body>
    

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

    <!-- script -->
    <script src="jquery.min_1.12.4.js"></script>
    <script>
        //두번째 li한테 배경색을 빨간색으로 변경해주세요
        //$("li:odd").css("backgroundColor","red");
        //$("li:eq(1)").css("backgroundColor","red");
        //$("li:contains('toggleClass')").css("backgroundColor","red");
        //$("li:nth-child(2)").css("backgroundColor","red");
        //$("li:nth-of-type(2)").css("backgroundColor","red");
        //$("li:nth-child(even)").css("backgroundColor","red");
        //$("li:nth-child(2n)").css("backgroundColor","red");

        //클릭 이벤트 메서드
        $(".btn1").click(function(){
            //$("li:nth-child(2)").css("backgroundColor","red");
            $("li:nth-child(2)").addClass("red");
        });
        $(".btn2").click(function(){
            $("li:nth-child(2)").removeClass("red");
        });
        $(".btn3").click(function(){
            $("li:nth-child(2)").toggleClass("red");
        });

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

Last updated

Was this helpful?