jQuery / Method / .toggleClass() - 선택한 요소에 클래스 값을 넣었다 뺐다 하는 메서드
.toggleClass()
.toggleClass()로 선택한 요소에 클래스(Class) 값을 넣었다 뺐다 할 수 있습니다.
문법
.toggleClass( className )
예를 들어
$( 'p' ).toggleClass( 'xyz' );
는, p 요소에 xyz 클래스가 없으면 추가하고, 있으면 제거합니다.
예제
버튼을 클릭하면 h1 요소에 ab 클래스 값이 추가되어 배경색이 생기고, 다시 버튼을 클릭하면 ab 클래스 값이 제거되어 배경색이 사라집니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> .ab { background-color: #f5f5f5; } </style> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> $( document ).ready( function() { $( 'button' ).click( function() { $( 'h1' ).toggleClass( 'ab' ); } ); } ); </script> </head> <body> <button>Click</button> <h1>Lorem Ipsum Dolor</h1> </body> </html>
참고
- 클래스에 값을 추가할 때는 .addClass(), 제거할 때는 .removeClass()를 사용합니다.
- jQuery / Method / .click()