클래스 속성 조작(‘classList’ property) : 요소의 클래스 목록을 DOMTokenList(유사 배열) 형태로 반환
add()와 remove() 메서드를 사용해 지정한 클래스 값을 추가 혹은 제거
element.classList.add() : 지정한 클래스 값을 추가
element.classList.remove() : 지정한 클래스 값을 제거
- ‘classList’ property 예시
<body><h1class="title heading">DOM 선택</h1><ahref="http://www.google.com/">google</a><pclass="text">content1</p><pclass="text">content2</p><pclass="text">content3</p><ul><li>list1</li><li>list2</li></ul><script>// .heading의 클래스를 가진 요소를 선택하여 h1Tag 변수로 할당let h1Tag = document.querySelector(".heading");
console.log(h1Tag.classList);// 해당 변수의 클래스 리스트에 test 값 추가
h1Tag.classList.add("test");
console.log(h1Tag.classList);// 해당 변수의 클래스 리스트에서 test 값 제거
h1Tag.classList.remove("test");
console.log(h1Tag.classList);</script></body>
클래스 리스트 예시 결과
4-2. 일반 속성 조작
조회하기 : Element.getAttribute(selector)
해당 요소에 지정된 값을 반환
설정(수정)하기 : Element.setAttribute(selector, 수정할 값)
지정된 요소의 속성 값을 설정
속성이 이미 있으면 값이 업데이트 / 없으면 지정된 이름과 값으로 새로운 속성 추가
삭제하기 : Element.removeAttribute(selector)
요소에서 지정된 이름을 가진 속성 제거
- 일반 속성 조작 예시
<body><h1class="title heading">DOM 선택</h1><ahref="http://www.google.com/">google</a><pclass="text">content1</p><pclass="text">content2</p><pclass="text">content3</p><ul><li>list1</li><li>list2</li></ul><script>// a태그의 요소를 찾아 변수 aTag로 할당// 변수 aTag의 href 속성의 값 조회let aTag = document.querySelector("a");
console.log(aTag.getAttribute("href"));// 변수 aTag의 href 속성의 값을 'https://www.naver.com/'으로 설정// 수정된 변수 aTag의 href 속성 값 조회
aTag.setAttribute("href","https://www.naver.com/");
console.log(aTag.getAttribute("href"));// 변수 aTag의 href 속성의 값을 삭제// 수정된 변수 aTag의 href 속성 값 조회
aTag.removeAttribute("href");
console.log(aTag.getAttribute("href"));</script></body>