let arr = [10,20,30];
배열에 값을 새롭게 추가할 때는 Array타입 객체 안에 들어있는
push
메소드를 사용한다ex) arr.push(40); console.log(arr) // 출력값 [10,20,30,40]
배열 속에 값을 삭제할 때는
pop
메소드를 사용한다<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .plain { font-size: 20px; font-weight: bold; } .err{ color: red; } </style> </head> <body> <div class="plain"> 잘못된 값입니다. </div> <button onclick="f();">글자색 바꾸기</button> <script> const f =()=>{ let myDiv = document.querySelector('.plain'); myDiv.classList.add('err'); } </script> </body> </html>
유사배열 (배열처럼
여러개의 값
을저장
하기 위해 만든것인데,특수한 경우
에 사용하기 위해 만든 타입들..)
💁🏻♀️ DOMTokenList 타입
배열
과 같이여러개의 값
을 저장할 떄 사용 (value 라는 key 값이자동
으로 추가됨)
📒 새로운 값을 추가하고 싶으면add
메소드를 사용한다.
객체의classList
라는key값
이 바로 DOMTokenList 타입이다.
- 일반 객체에 length 프로퍼티가 존재하는 경우 유사 배열 객체라고 말합니다.
- 유사 배열 객체의 대표적인 예시로 함수의 arguments 객체가 존재합니다.
📒 기존에 있는 요소를삭제
하고 싶으면remove
메소드를 사용한다
💁🏻♀️ Properties
📒
length
DOMTokenList 항목의 수를 조회한다.
📒value
DOMTokenList의 항목을 DOMString으로 조회한다.
💁🏻♀️ Methods
📒
add()
토큰 목록에 항목을 추가한다.
📒remove()
인수로 지정된 항목을 토큰에서 제거한다.
📒replace()
기존 토큰을 주어진 인수로 대체한다.
📒contains()
인수로 지정된 토큰이 포함되어 있으면 true, 그렇지 않으면 fasle 값
<div class='a b c'></div> myDiv.classList = ['a', 'b', 'c'];
d라는 클래스, e라는클래스랑 f라는 클래스 세개 동시에 추가 원하면? ['a','b','c','d','e','f']
const f =()=>{ let myDiv = document.querySelector('.plain'); myDiv.classList.add('err', 'a', 'b', 'c'); }
<div id="myTarget" class="a b c d e f g h"> 현재 이 태그의 클래스는 a, b, c, d, e, f, g, h 입니다. </div> <input type="text" placeholder="삭제할 클래스 이름을 써주세요!"/> <button onclick="f2();">클래스 삭제하기</button> <script> const f2 = ()=>{ //🌟 1. input 태그의 값을 가져온다. let myInput = document.querySelector('input'); myInput.value = 'a'; //🌟 2. #myTarget div 태그의 클래스를 삭제한다. let myTargetDiv = document.querySelector('#myTarget'); myTargetDiv.classList.remove(myInput.value); //🌟 3. #myTarget div 태그의 내용물을 변경한다. myTargetDiv.textContent = `현재 이 태그의 클래스는 ${myTargetDiv.className} 입니다.`; }
className과 classList는 모두 HTML 요소의 클래스(class)
에 접근하고 조작하는 데 사용되는 프로퍼티 및 메서드입니다. 그러나 사용 방식과 목적에서 약간의 차이
가 있습니다.
className은 HTML
요소의 클래스
속성의 값을 가져오거나 설정하는 데 사용됩니다. 클래스 속성은 공백으로 구분된 여러 클래스 이름을 가질 수 있으며, className을 사용하여 이 클래스 이름들을 문자열로 조작할 수 있습니다. 클래스 이름을 바로 설정하거나 가져올 수 있습니다.
💁🏻♀️예를들어,
const element = document.getElementById('myElement'); // 클래스 이름 가져오기 const currentClasses = element.className; // 클래스 이름 설정 element.className = 'newClass anotherClass';
classList는
DOMTokenList
객체를 반환하며, 이를 사용하여클래스
를 추가, 제거, 토글, 확인 등 다양한 조작을 할 수 있습니다. classList를 사용하면 클래스 조작을 좀 더 편리하게 처리할 수 있습니다. classList에는add
,remove
,toggle
,contains
등의 메서드가 포함되어 있습니다.
💁🏻♀️예를들어,
const element = document.getElementById('myElement'); // 클래스 추가 element.classList.add('newClass'); // 클래스 제거 element.classList.remove('oldClass'); // 클래스 토글 element.classList.toggle('active'); // 특정 클래스가 있는지 확인 const hasClass = element.classList.contains('someClass');
🌟 잠깐! className과 다른 점을 살펴봅시다. 🤨
📍
className
은 클래스를 추가하려 할 때, 이미 같은 이름의 클래스가 있다면중복해서 추가
해버려요.
📍 그런데,classList.add
를 사용하면 달라요. 이미 클래스 속성에 같은 이름의 클래스가 있으면 중복으로 추가하지 않아요!