
DOM
- HTML이나 XML에서 프로그래밍을 위한 인터페이스
- 자바스크립트 등의 언어가 각 요소에 접근하여 조회하거나 추가,변경, 삭제 등을 시킬 수 있도록 도와 줌
- DOM은 노드와 객체로 웹 문서의 구조를 논리적으로 표현
- 노드는 HTML문서를 트리 모양의 계층 구조로 만들 때 각 지점이 되는 곳
- HTML문서는 하나 이상의 노드로 구성 된 collection이라 할 수 있음
- 노드는 내부적으로 요소 노드, 속성 노드, 텍스트 노드 등 여러 유형으로 구분
HTML 요소에 접근하는 방법
- getElementById()
- getElementsByTagName()
- getElementsByClassName()
- getElementsByName()
- querySelector()
- querySelectorAll()
각각 접근하는 방법: document.getElementById() …
여러개를 배열형식을 접근하는 방법 : document.images, document.forms, document.links…
HTML요소를 변경하는 방법
- HTML요소 선택 후 속성이나 컨텐츠의 변경이 가능
-
선택한 요소.setAttribute(’속성명’, 변경할 값)
-
선택한 요소.속성명 = 변경할 값
ex) img = document.querySelector('.image')
img.setAttribute('src', '변경할 src')
img.src = '변경할 src'
HTML요소를 추가하는 방법
- createElement()로 요소 생성
- createAttribute()로 요소의 속성 생성
- setAttributeNode()로 요소에 연결
- crateTextNode()로 텍스트 노드 생성 후
- appendChild()를 이용해 자식으로 연결
const list = document.querySelectorAll('li')
for (let list of lists) {
list.onclick = () => {
const lists = document.createElement('li')
const attribute = document.createAttribute('class')
attribute.value = 'item'
lists.setAttributeNode(attribute)
const texts = list.innerText + '추가할 내용';
const textNode = document.createTextNode(texts)
lists.appendChild(textNode)
list.parentElement.appendChild(lists)
}
}
HTML요소를 삭제하는 방법
- removeChild()를 통해 특정 요소 삭제 가능
- BOM의 location과 reload() 메서드 사용 가능
documnet.querySelector('item').onclick = function(){
location.reload()
}
const ul = document.querySelector('ulists')
document.querySelector('item2').onclick = function(){
const target = document.querySelectorAll('li')[1];
ul.removeChild(target)
}
document.querySelector('btn').onclick = function() {
if (ul.children.length) {
ul.removeChild(ul.children[0]);
}
}
BOM
- BOM은 브라우저가 제공하는 여러 기능에 대하여 객체의 구조로 이해하는 모델
BOM의 메서드
- 각 HTML요소와 속성에 접근할 수 있도록 하는 메서드
- window
- 윈도우에 대한 정보를 갖는 최상위 객체
- 툴바, 스크롤 바를 포함하는 브라우저 영역 크기
- window.outerWidth
- window.outerHeight
- 브라우저 컨텐츠 영역의 실제 크기
- window.innerWidth
- window.innerHeight
- screen
- 스크린에 대한 정보를 갖는 객체
- 브라우저 크기 관계 없이 모니터의 픽셀 단위 크기
- screen.width
- screen.height
- 모니터의 픽셀 단위 크기에서 하단의 태스크 바를 제외한 크기
- screen.availWidth
- screen.availHeight
- document
- 문서를 조작할 수 있는 객체
- document.write()
- 매개변수로 전달되는 텍스트나 HTML요소를 웹페이지에 출력, 이미 로드된 웹 문서의 내용 모두를 document.write()의 결과로 대체
- location
- 현재 웹 문서의 주소와 관련된 정보를 갖는 객체
- location.href
- location.hostname
- location.pathname
- location.protocol
- location.assign : 주어지는 URL로 화면 이동 (히스토리 남음)
- location.replace : 주어지는 URL로 화면 대체 (히스토리 제거)
- history
- 뒤로 가기, 앞으로 가기 등 브라우징 이력에 대한 정보를 갖는 객체
- navigator
- 사용자의 브라우저에 대한 정보를 갖는 객체
- appCodeName : 브라우저의 코드 네임 (Mozilla)
- appName : 브라우저의 이름 (Netescape)
- appVersion : 브라우저의 버전
- language : 브라우저의 언어
- onLine : 온라인 상태 여부
- platform : 브라우저 플랫폼 정보
- userAgent : 헤더 정보
- geolocation : 사용자 위치 정보
- popup alert
- alert(), confirm(), prompt()와 같은 팝업 알림 기능 갖는 객체
- timing
- setTimeout(), setInterval()의 타이밍 이벤트 기능을 갖는 객체
- cokies
- 사용자 컴퓨터에 사용자의 웹페이지 관련 정보를 저장, 관리하는 기능을 갖는 객체