hasClass()

hasClass() 메서드는 선택한 요소에 지정한 클래스가 있으면true를 반환하고, 없으면 false를 반환합니다.

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

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

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

    <!-- script -->
    <script src="jquery.min_1.1.24.js"></script>
    <script>
        // li를 클릭하면 li에게 배경색을 빨간색으로 변경해주는 것(red클래스 추가)
        // $("li").click(function(){
        //     $(this).addClass("red");
        // });
        // li를 클릭하면 li에게 배경색을 빨간색으로 변경해주는 것(클래스 'select'가 있는 요소한테)
        $("li").click(function(){
            if($("li").hasClass("select")){
                $(".select").addClass("red");
            }
        });
    </script>

</body>
</html>

Last updated

Was this helpful?