본문 바로가기
개발 공부 일지/JavaScript

자바스크립트 - HTML 속성 다루기

by yelimu 2024. 7. 16.

DOM : html 문서를 객체로 표현한 것 (속성과 속성값을 갖는) 

 

브라우저가 콘텐츠를 화면에 보여주기 위해 html 을 해석할 때 DOM 객체가 만들어진다 

 

이때 html의 각각의 속성은 DOM 요소 노드의 프로퍼티가 된다

ex.

<li class="클래스" id="아이디" href="https://blabla.com"> 어쩌구 </li>

라는 html 코드가 있을때

 

const list = document.querySelector("아이디")  ->  li 요소에 접근 -> DOM 요소 노드

이때 list.id 또는 list.className 또는 list.href 이런 식으로 요소 노드의 프로퍼티로 사용한다는 뜻

 

class 속성은 className 이라는 프로퍼티로 생성됨 

 

참고.

속성 이름은 모두 소문자로 변환되어 동작한다. 

https://developer.mozilla.org/ko/docs/Glossary/Attribute

 

특성 - MDN Web Docs 용어 사전: 웹 용어 정의 | MDN

특성(attribute)은 HTML이나 XML element를 확장해 동작 방식을 바꾸거나 메타데이터를 제공합니다.

developer.mozilla.org

 

BUT 모든 속성이 해당되는 것은 아님

html 표준 속성에 해당하는 것들만 요소 노드의 프로퍼티가 된다

<ol id="tomorrow" href="https://www.codeit.kr">
      <li class="item"><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript">자바스크립트 공부</a></li>
	<li class="item">뮤지컬 공연 예매</li>
	<li class="item">유튜브 시청</li>

 

const tomorrow = document.querySelector('#tomorrow');
const item = tomorrow.firstElementChild;
const link = item.firstElementChild;

 

console.log(tomorrow.href) -> undefined 으로 반환됨 (ol 태그에 href 속성은 html표준 속성이 아님)

프로퍼티에 직접 접근하는 방식으로는 HTML 비표준 속성에 접근할 수 없음 

 

▼ 메서드를 이용하면 표준/비표준 상관없이 모든 속성에 접근 가능하다


HTML 속성을 다루기 위한  DOM 메서드 

 

elem.getAttribute('속성') 으로 모든 속성에 접근 가능하다 (표준/비표준 상관없이)

console.log(tomorrow.getAttribute('href')); -> tomorrow 의 href 속성에 접근 가능 (연결해둔 link 출력)

console.log(item.getAttribute('class')); -> item

 

elem. setAttribute( '속성', '값' )으로 속성 추가/수정 하기 (이미 존재하면 수정/없으면 추가) 

tomorrow.setAttribute('class', 'list'); tomorrow라는 변수에 담긴 요소에 class 속성을 list 로 추가

link.setAttribute('href', 'https://~'); link 라는 변수에 담긴 요소에 href 속성을 ~ url로 수정

 

elem. removeAttribute('속성') 으로 속성 제거하기

tomorrow.removeAttribute('href'); 
tomorrow.removeAttribute('class'); 

 


요소노드.속성 -> 표준 속성만 접근

요소노드.getAttribute('속성') -> 모든 속성에 접근 

 

class 속성에 접근할 때 

요소노드.className

요소노드.getAttribite('class')