나의 공부 일기

JavaScript) DOM(Document Object Model) 본문

JavaScript/정리

JavaScript) DOM(Document Object Model)

곽병권 2024. 3. 13. 19:38
728x90

DOM

웹 페이지의 구조화된 표현을 프로그래밍으로 조작할 수 있는 인터페이스를 제공하는 API 입니다.

 

쉽게 말해서 HTML 파일에 있는 클래스명이나 태그명등을 가져와서 변경하거나 새로운 요소를 추가하거나 제거하거나등 웹페이지를 조작하는것을 말합니다.

 

DOM으로 할 수 있는것

document.getElementById('아이디명');

- 아이디명에 해당하는 요소를 가져옵니다.

 

클래스명과 태그명은 중복이 가능하므로 Elements 입니다.

document.getElementsByClassName('클래스명');

- 클래스명에 해당하는 요소들을 모두 가져옵니다.

 

document.getElementsByTagName('태그명');

- 태그명에 해당하는 요소들을 모두 가져옵니다.

 

document.querySelector('#아이디명 or .클래스명'); 

- 클래스명 or 아이디명에 해당하는 요소를 가져옵니다.

 

HTML에서 클래스명은 여러개에 지정할 수 있는데 이때 한번에 값을 가져오려면
document.querySelectorAll('.클래스명'); 을 사용합니다

- 클래스명에 해당하는 요소를 모두 가져옵니다.

 

이렇게 가져온 값을 변수에 지정하여 [인덱스번호] 로 그 인덱스에 해당하는 요소값을 가져올 수 있습니다.

 

콘텐츠 수정하기

모든 요소에는 textContent 와 innerHTML 프로퍼티가 있습니다.

이 프로퍼티를 통해 요소의 콘텐츠를 가져오거나 수정할 수 있습니다.

 

textContent : HTML 태그를 모두 제거하고 순수한 텍스트 데이터만 제공합니다.

innerHTML : HTML 태그를 그대로 제공합니다.

 

위에서 가져온 요소명을 

let h2 = document.querySelector('#title');

이렇게 변수에 저장한 후 

 

h2.textContent = 'HELLO!';

textContent를 사용해준다면 h2 태그를 HELLO! 로 변경합니다.

이는 순수한 텍스트 데이터만 제공하기 때문에

h2.textContent = '<span>HELLO!</span>';

이처럼 태그로 감싸주어도 이 태그도 텍스트로 적용하여 변경해줍니다.

 

 

여기서 innerHTML를 사용한다면 태그를 인식하여 그 태그까지 적용하여 수정해줍니다.

h2.textContent = '<span>HELLO!</span>';

 

 

위에서 dom으로 요소를 가져왔을때

그 요소를 바로 수정해줄 수도 있는데,

document.querySelector('body').innerHTML = '<strong>HELLO!</strong>';

이렇게 body태그를 가져와서 body태그를 변경해줄 수 도 있습니다.

이러면 한번에 변경이 되므로 주의해서 사용해야 합니다.

 

 

let input = document.querySelector('input');
input.setAttribute('placeholder', '아이디');

이렇게 태그내의 속성값도 setAttribute로 수정해줄 수 있습니다.

setAttribute('속성명','변경값'); 

 

 

input.removeAttribute('placeholder');

아예 지울 수도 있습니다.

removeAttribute('속성명');

 

 

요소를 가져와 그 요소의 style도 수정해줄 수 있습니다.

let helloItem = document.querySelector('.hello');
console.log('helloItem: ', helloItem);

helloItem.style.color = 'white';
helloItem.style.backgroundColor = 'black';

 

요소에 클래스를 추가해줄 수 있습니다.

helloItem.classList.add('dark')

 

반대로 클래스를 삭제할 수 도 있습니다.

helloItem.classList.remove('dark')

 

 

https://developer.mozilla.org/en-US/docs/Web/API/Element

 

Element - Web APIs | MDN

Element is the most general base class from which all element objects (i.e. objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.

developer.mozilla.org

 

이 사이트에서 그때그때 필요한것들을 찾아서 사용해주면 됩니다.

728x90

'JavaScript > 정리' 카테고리의 다른 글

JavaScript) 변수 / 자료형  (1) 2024.02.13