상세 컨텐츠

본문 제목

properties(속성), attributes(특성) 차이점

JavaScript

by 폴리프레임 2024. 9. 17. 11:31

본문

반응형

1. Attributes (HTML 특성)

 

  • Attributes는 HTML 문서에서 DOM 요소에 직접 작성된 입니다.
  • 이 값은 브라우저가 요소를 처음 읽을 때 설정됩니다.
  • HTML 자체에서 볼 수 있는 정보이며, 주로 요소의 초기 상태를 나타냅니다.
  • 예를 들어 <input type="text" value="Hello" id="myInput">에서 type, value, id는 모두 attributes입니다.
  • getAttribute() 및 setAttribute() 메서드를 사용하여 HTML 특성을 가져오거나 설정할 수 있습니다.
<input type="text" value="Hello" id="myInput">


// 요소 선택
let input = document.getElementById('myInput');

// Attribute 값을 가져오기
console.log(input.getAttribute('value'));  // "Hello"

// Attribute 값을 설정하기
input.setAttribute('value', 'New Value');

 

2. Properties (JavaScript 속성)

 

  • Properties는 DOM 요소의 JavaScript 객체에 저장된 입니다.
  • DOM 요소는 JavaScript 객체로 표현되며, 이 객체에는 여러 속성이 존재합니다. 이 속성들은 HTML 특성과 초기값은 동일할 수 있지만, 변경하면 서로 독립적으로 동작할 수 있습니다.
  • 예를 들어, <input> 요소의 value 속성은 HTML 문서에 선언된 value attribute와는 별개로 JavaScript에서 실시간으로 변경되고 관리됩니다.
<input type="text" value="Hello" id="myInput">


// 요소 선택
let input = document.getElementById('myInput');

// Property 값을 가져오기
console.log(input.value);  // "Hello" (초기 HTML value 값)

// Property 값을 설정하기
input.value = 'New Value';  // input 요소의 값이 'New Value'로 변경됨

 

3. 주요 차이

 

  • Attributes는 HTML에 정의된 값이고, properties는 JavaScript 객체의 상태를 나타냅니다.
  • Attributes는 페이지가 로드된 후에는 일반적으로 변경되지 않지만, properties는 동적으로 변할 수 있습니다.
  • Attributes는 getAttribute() 및 setAttribute()로 조작하고, properties는 점 표기법으로 직접 접근할 수 있습니다.
<input type="text" value="Hello" id="myInput">

------
let input = document.getElementById('myInput');

// Attribute와 Property의 차이 확인
console.log(input.getAttribute('value'));  // "Hello" (HTML 특성 값)
console.log(input.value);  // "Hello" (초기 값이 동일)

// Property 값을 변경
input.value = 'Goodbye';
console.log(input.getAttribute('value'));  // 여전히 "Hello" (변경되지 않음)
console.log(input.value);  // "Goodbye" (변경됨)

// Attribute 값을 변경
input.setAttribute('value', 'New Value');
console.log(input.getAttribute('value'));  // "New Value" (변경됨)
console.log(input.value);  // 여전히 "Goodbye" (property는 그대로)

 

관련글 더보기