JS : CSS 클래스 활용 속성/메서드

 

classList, className

CSS 클래스를 자바스크립트와 연동하여 다양한 동작 표현을 진행할 수 있습니다.

 

 

DOM.className = '추가클래스명'

원하는 DOM 대상에 새로운 클래스명을 적용할 수 있습니다.

<p id="target">TAG</p>
const target = document.getElementById('target')
target.className = 'a'

 

* className 속성 사용 시 대입연산자를 사용하여 클래스를 2개 이상 적용 시 마지막 클래스만 적용됩니다.

const target = document.getElementById('target')
target.className = 'a'
target.className = 'b'

 

 

* 추가 클래스를 적용하고 싶은 경우는 복합연산자를 사용합니다.

주의) 복합연산자로 연결하는 추가 클래스를 공백 없이 입력 시 기존 클래스의 이름이 변경되는 것으로 인식합니다.

 


 

 

DOM.classList.add('추가클래스명')

원하는 DOM 대상에 새로운 클래스명을 적용할 수 있습니다.

 * className과 다르게 공백 또는 복합연산자 없이 메서드 구조로 실행되어 별도의 클래스등록이 가능합니다.

* 동시에 2개 이상의 클래스를 콤마(,)로 구분하여 선언할 수 있습니다.

<p id="target">TAG</p>
const target = document.getElementById('target')
target.classList.add('a')
target.classList.add('b')
target.classList.add('c', 'd')

 


 

DOM.classList.remove('제거클래스명')

원하는 DOM 대상에 적용된 클래스를 제거할 수 있습니다.

* 2개 이상의 클래스를 제거하고 싶은 경우는 add방식과 동일하게 콤마(,)로 구분하여 작성합니다.

<p id="target" class="a b">TAG</p>
const target = document.getElementById('target')
target.classList.remove('b')

 

 

const target = document.getElementById('target')
target.classList.remove('a', 'b')

 


 

DOM.classList.toggle('토글클래스명')

원하는 DOM 대상 클래스 적용 상태에 따라 추가/제거를 실행합니다.

* 스위치 ON/OFF 와 같이 구조를 생각해보시면 쉽습니다.

* ON이 되어있을 때 누르면 OFF가 되고 

  OFF가 되었을 때 누르면 ON이 됩니다.

* 이 것을 클래스로 바꿔 생각해보면

a 클래스가 적용 된 경우 toggle 적용 시 a 클래스가 제거되고

a 클래스가 제거 된 상태라면 toggle 적용 시 a 클래스가 재생성됩니다.

 

<p id="target" class="a">TAG</p>
const target = document.getElementById('target')
target.classList.toggle('a')

 

 

 

<p id="target" class="">TAG</p>
const target = document.getElementById('target')
target.classList.toggle('a')

 


 

DOM.classList.replace('기존', '변경')

* 기존 클래스를 다른 이름으로 변경합니다.

<p id="target" class="a">TAG</p>
const target = document.getElementById('target')
target.classList.replace('a', 'b')

 

 

 

 

* 기존 클래스가 2개 이상인 경우 replace로 설정한 기준 클래스만 변경되고 그 외 클래스는 변동되지 않습니다.

<p id="target" class="a c">TAG</p>
const target = document.getElementById('target')
target.classList.replace('a', 'b')

 

 

 

 

 

 


 

DOM.classList.contains(클래스 유무 확인)

* 클래스의 존재 유무를 확인합니다.(jquery의 hasClass와 의미 동일)

* true or false를 반환합니다.

<p id="target" class="a c">TAG</p>
const target = document.getElementById('target')
target.classList.contains('a') //true
  Comments,     Trackbacks