본문 바로가기

WEB/Javascript

[JS] 브라우저 DOM

https://www.w3schools.com/js/js_htmldom.asp

 

 

JavaScript HTML DOM

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

웹 브라우저에서 다루는 객체(BOM) 중 가장 최상위는 window이며 DOM은 window의 하위객체

 

DOM(Document Object Model) 문서객체모델로 여러 모델이 있지만 여기선 HTML DOM으로 통일한다.

Core, XTML, HTML

 

웹 브라우저가 문서를 읽는(객채가 생성되는) 두 가지 방법이 있다.

정적 - html 요소를 읽는 것

동적 - javascript 를 통해 html요소 혹은 그 속성을 생성하거나 수정할 수 있다.(스크립트언어를 통해 조작가능하다.)

 

 

DOM 은 트리 구조이다. 

<html> 
    <head> 
    	<title>"My title"</title> 
    </head> 
    <body> 
    	<h1>A heading</h1> 
    	<a href="#">Link text</a> 
    </boody> 
</html>

<출처: 위키피디아 백과사전>

아래 참고되는 코드를 살펴보자

사용된 DOM 객체

document : 어떤 html요소에 접근하고 싶다면 document을 불러와야한다.

addEvenListener() : 이벤트발생시 처리할 함수 

alert() : window 객체 메소드이다. 따라서 window.을 생략하고 alert()만 사용할 수 있다.

 

const btn = document.querySelector('.btn');
//문서 내에서 주어진 선택자를 만족하는 첫 번째 Element를 반환한다.

btn.addEventListener('click',(event) => {
  alert('경고창!\n연습입니다.')
  //window 객체 메소드로 html안에 없던 요소를 생성해서 알림을 보낸다.
})

 

document 객체 : document.querySelector('.class이름')

1. 요소 찾기

메소드  
document.getElementById(id) 요소의 id로 찾는다.
document.getElementsByTagName(name) 태그 이름으로 찾는다. (h1,article,img,a...)
document.getElementsByClassName(name) 요소의 class로 찾는다.
document.querySelector(selectors) 선택자로 찾기

이외로 html의 객체로 

document.['anchor','body','cookie','doctype','head','forms','imags'.....]

등으로 찾아낼 수 있다.

 

2. 생성 혹은 삭제

메소드  
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
   
document.write(text) Write into the HTML output stream

 

3.이벤트 처리

메소드  
document.getElementById(id).onclick = function(){code} 클릭 이벤트 발생시 처리할 함수 추가하기

EventTarget.addEventListener(type,listener) 메소드

EventTarget의 대상으로 Element , Document, Window 을 주로 쓰지만 모든 객체가 대상이된다.

 

btn.addEventListener('click',(event) => {
  alert('경고창!\n연습입니다.')
})

타겟 : 'btn' (class이름이 btn인 html요소인 버튼) 

타입 : 'click'

listener: 콜백함수

 

1. type : 이벤트 유형

https://developer.mozilla.org/ko/docs/Web/Events#%EA%B0%80%EC%9E%A5_%EC%9D%BC%EB%B0%98%EC%A0%81%EC%9D%B8_%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC

 

이벤트 참조 | MDN

DOM 이벤트는 발생한 흥미로운 것을 코드에 알리기 위해 전달됩니다. 각 이벤트는 Event 인터페이스를 기반으로한 객체에 의해 표현되며 발생한 것에 대한 부가적인 정보를 얻는데 사용되는 추가

developer.mozilla.org