반응형
property 방식의 요소 속성명 확인
요소.속성명 (확인)
- HTML 요소의 속성을 자바스크립트 객체의 속성처럼 접근함
- DOM 객체의 속성(property)에 접근
- HTML과 약간 다르게 동작할 수 있음
- input.value, img.src, checkbox.checked 등
- 실제 화면에서 바뀐 현재 상태값을 반영함
- 자바스크립트에서 가장 자주 쓰임
- 클래스 속성을 확인하는 경우 className 사용
// [문법]
요소.속성명
<input type="text" value="text">
const input = document.querySelector('input');
console.log(input.value); // input에 입력된 값을 확인
요소.속성명 (수정)
// [문법]
요소.속성명 = "변경할 속성값"
<input type="text" value="text">
const input = document.querySelector('input');
input.value = "text2"
getAttribute / setAttribute 사용
- HTML에 명시된 속성(attribute)을 직접 가져오거나 수정
- 속성명은 문자열로 작성
- 실제 HTML 태그에 작성된 값을 기준으로 동작함
- 초기의 값 확인/수정
getAttribute()
- 요소의 속성 확인
// [문법]
요소.getAttribute("속성")
<input type="text" value="temp"class="box">
const input = document.querySelector('input');
console.log(input.getAttribute('class')); // ⇒ temp
setAttribute()
- 요소의 속성 수정
// [문법]
요소.setAttribute("속성명", "변경할 속성값")
<input type="text" value="temp">
const input = document.querySelector('input');
input.setAttribute('value', 'temp2');
console.log(input.getAttribute('value')); // ⇒ temp2
“왜 .value와 getAttribute('value')의 값이 다를까?”
- DOM 속성(property)은 현재 상태를 반영하고, HTML 속성(attribute)은 초기값을 유지.
- 단, classList.add()나 className = "..."처럼 class 값을 바꾸는 조작을 하면, getAttribute('class')로 조회를 해도, 변경된 값을 가져옴(w? 둘 다 class HTML 속성을 직접 바꾸기 때문에)
기준의 출발점: HTML 파싱
- 브라우저는 페이지를 로드할 때 다음 과정을 거침:
- HTML 코드 파싱 → DOM 트리 생성
- HTML 속성(attribute)을 읽어서, 대응하는 DOM 속성(property)에 반영
- 이후에는 자바스크립트나 사용자 동작에 의해 DOM 속성만 계속 변화
하지만 getAttribute()는 여전히 HTML 태그 안에 원래 적혀있던 문자열 그대로를 반환
항목 | .속성명(DOM 속성) | Attribute (HTML 속성) |
어디서 온 값? | 브라우저가 만들어낸 DOM 객체의 값 | HTML 태그에 직접 적힌 문자열 |
언제 바뀌나? | JS나 사용자 동작에 따라 바뀜 | 바뀌지 않음 (직접 setAttribute 해야 함) |
어떤 정보 제공? | 현재 상태 | 초기 선언된 값 |
예시 | input.value, img.src, el.checked | getAttribute('value'), 'src', 'checked' 등 |
속성 조작 방식에 따른 .속성명과 getAttribute() 결과 비교표
속성 변경 방식 | .속성명 결과값 | getAttribute() 결과값 | 설명 |
초기 상태 | "초기값" | "초기값" | HTML 태그에 적힌 상태 |
.속성명 = "변경값" | "변경값" | "초기값" | DOM 상태만 변경됨 |
setAttribute("속성", "변경값") | "변경값" (동기화됨) | "변경값" | HTML 속성 변경 → DOM 속성도 반영되는 경우 있음 |
.className = "변경값" | "변경값" | "변경값" | 기존 클래스를 문자열로 직접 덮어쓰기 (setAttribute('class', …)과 동일 효과) |
.classList.add("new") | "기존 + new" 또는 변경된 class 전체 | "기존 + new" 또는 동일 | classList는 내부적으로 setAttribute('class', …)처럼 작동함 |
<input id="myInput" value="hello">
const input = document.getElementById('myInput');
// DOM 상태 (변경 가능)
input.value = "world";
console.log(input.value); // 👉 "world"
// HTML 원본 속성
console.log(input.getAttribute("value")); // 👉 "hello"
/*
※SetAttritue로
input.setAttribute("value", "wolrd") 값을 바꿨을 경우
input.getAttribute("value")도 👉 world 바꾼 값이 됨
*/
✓ value는 내 생각, getAttribute('value')는 주민등록증, class는 명찰
setAttribute는 주민등록증을 직접 수정
classList.add는 명찰에 스티커를 붙이는 것
className =은 명찰을 새로 만드는 것
자주 사용되는 속성과 메서드
요소 속성/메서드 설명
요소 | 속성/메서드 | 설명 |
input, textarea | .value / getAttribute('value') | 입력된 값 또는 초기 value 확인/변경 |
a (링크) | .href / getAttribute('href') | 링크 주소 확인/변경 |
img | .src / getAttribute('src') | 이미지 경로 확인/변경 |
모든 요소 | .id, .className, .style | ID, 클래스명, 스타일 제어 |
모든 요소 | getAttribute('data-*') | 커스텀 데이터 속성 읽기 |
모든 요소 | .setAttribute('title', '...') | title, alt 등 속성 추가/변경 |
반응형