WEB/JavaScript
Js - dom 문서 객체 모델
jomericano
2022. 6. 13. 18:42
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>자바스크립트 문서객체 모델 </title>
<link rel="stylesheet" href="../css/normalize.css">
<style>
table{
border-collapse: collapse;
border-spacing: 0;
}
th, td{
padding: 10px 20px;
border: 1px solid #000;
}
</style>
</head>
<body id = "body">
<h1>자바스크립트 문서객체 모델 </h1>
<h2>개요</h2>
<p>텍스트파일로 만들어져있는 html 문서를 브라우저에 시각적으로 나타내려면 (렌더링)
먼저, 문서의 내용을 브라우저가 이해할 수 있는 형태로
메모리에 업로드하는 과정(파싱parsing)이 선행되야 함 </p>
<p> 파싱과정을 통해 메모리에 업로드된 결과는 DOM이라고 부르는데,
이것은 자바스크립트를 통해 문서의 내용에 접근해서 동적으로 변경할 수 있음</p>
<p>한편, DOM으로 구성된 문서내 객체들은 속성과 메서드로 구성된
DOM API를 이용해서 동적으로 웹페이지 내용을 변경할 수 있음 </p>
<h2> DOM tree 구성 노드 </h2>
<p> document node : 트리의 최상위 요소
DOM tree에 접근하기 위한 진입점(entry point) </p>
<p> element node : HTML상의 요소를 의미 </p>
<p> attribute node : HTML상의 요소내 속성을 의미</p>
<p> text node :HTML의 요소 내 텍스트를 의미</p>
<h2>요소 찾기 : dom query </h2>
<p>하나의 요소를 id 선택자로 찾으려면 document.getElementById 사용</p>
<p>하나의 요소를 class 선택자로 찾으려면 document.querySelector 사용,
찾은 요소가 복수여도 하나만 선택 </p>
<p id = "one" class="first">시간은 금이라구 친구</p>
<p id = "two" class="first">시간은 금이라구 친구!!!!!!!</p>
<p id = "three">시간은 정말 금이라구 친구!!!!!!!!!</p>
<script>
const one = document.getElementById('one');
one.style.color = 'red';
const first = document.querySelector('.first');
first.style.fontWeight = 'bold';
document.write('id: one - ', one, '<br>');
document.write('class: first - ', first, '<br>');
</script>
<hr>
<p>여러 요소들을 태그이름으로 찾으려면 document.getElementsByTagName 을 사용,
반환값은 HTMLcollection(유사배열) 객체에 저장 </p>
<p>여러 요소들을 클래스 이름으로 찾으려면 document.getElementsByClassName 을 사용,
반환값은 HTMLcollection(유사배열) 객체에 저장 </p>
<p>여러 요소들을 클래스 선택자로 찾으려면 document.querySelectorAll 을 사용,
반환값은 NodeList객체(유사 리스트)에 저장 </p>
<script>
let p = document.getElementsByTagName('p');
p[9].style.fontStyle = 'italic'
let firsts = document.getElementsByClassName('first');
firsts[0].style.textDecoration = 'underline';
firsts[1].style.textDecoration = 'underline';
firsts = document.querySelectorAll('.first');
firsts[0].style.background = 'skyblue';
firsts[1].style.background = 'skyblue';
document.write('p tag 개수 -', p.length, '<br>');
document.write('first class 개수 -', firsts.length, '<br>');
</script>
<hr>
<h2>속성에 접근</h2>
<p>특정 요소의 속성을 설정하려면 setAttribute를 사용</p>
<div><img id = "img1"></div>
<script>
let img1 = document.getElementById('img1');
img1.setAttribute('src','/img/game.png'); // 이런식으로 동적으로 제어하면 검사로 확인가능
// 실행해야만 내용이 뜸 -> 크롤링에 의한 보안 더 강화됨
</script>
<hr>
<h2> 새로운 요소 추가</h2>
<p>태그이름을 인자로 전달해서 문서상에 새로운 요소를 생성하려면 createElement 사용</p>
<p>지정한 요소를 특정 요소의 자식요소로 추가하려면 appendChild 사용</p>
<p>텍스트 노드를 추가하려면 createTextNode를 사용 </p>
<div id = "img2"></div>
<script>
let img = document.createElement('img');
img.setAttribute('src', '/img/plane.png');
let img2 = document.getElementById('img2');
img2.appendChild(img);
</script>
<div id="gugun"></div>
<script>
let gugunlist =
['시/군/구','동작구','관악구','구로구','서초구','강남구'];
let gugun = document.getElementById('gugun');
let select = document.createElement('select');
// for(let i=0; i < gugunlist.length; ++i) { 아니면
for (let val of gugunlist) { //gugunlist에서 값이 없을때까지 값 가져옴
//구 이름을 추가하기 위해 option 요소 생성
let option = document.createElement('option');
//option요소에 추가할 텍스트내용 생성
let gu = document.createTextNode(val);
//생성한 텍스트노드를 option 요소에 자식요소로 추가
option.appendChild(gu);
// 생성한 option요소를 select 요소에 자식요소로 추가
select.appendChild(option);
}
// 생성한 select 요소를 div요소에 자식요소로 추가가
gugun.appendChild(select);
</script>
<select>
<option></option>
</select>
<hr>
<!-- <script>-->
<!-- let table = document.createElement('table');-->
<!-- let thead = document.createElement('thead');-->
<!-- let tbody = document.createElement('tbody');-->
<!-- table.appendChild(thead);-->
<!-- table.appendChild(tbody);-->
<!-- // Adding the entire table to the body tag-->
<!-- document.getElementById('body').appendChild(table);-->
<!-- // Creating and adding data to first row of the table-->
<!--let row_1 = document.createElement('tr');-->
<!--let heading_1 = document.createElement('th');-->
<!--heading_1.innerHTML = "이름";-->
<!--let heading_2 = document.createElement('th');-->
<!--heading_2.innerHTML = "국어";-->
<!--let heading_3 = document.createElement('th');-->
<!--heading_3.innerHTML = "영어";-->
<!--let heading_4 = document.createElement('th');-->
<!--heading_4.innerHTML = "수학";-->
<!--row_1.appendChild(heading_1);-->
<!--row_1.appendChild(heading_2);-->
<!--row_1.appendChild(heading_3);-->
<!--row_1.appendChild(heading_4);-->
<!--thead.appendChild(row_1);-->
<!--// Creating and adding data to second row of the table-->
<!--let row_2 = document.createElement('tr');-->
<!--let row_2_data_1 = document.createElement('td');-->
<!--row_2_data_1.innerHTML = "혜교";-->
<!--let row_2_data_2 = document.createElement('td');-->
<!--row_2_data_2.innerHTML = "99";-->
<!--let row_2_data_3 = document.createElement('td');-->
<!--row_2_data_3.innerHTML = "98";-->
<!--let row_2_data_4 = document.createElement('td');-->
<!--row_2_data_4.innerHTML = "97";-->
<!--row_2.appendChild(row_2_data_1);-->
<!--row_2.appendChild(row_2_data_2);-->
<!--row_2.appendChild(row_2_data_3);-->
<!--row_2.appendChild(row_2_data_4);-->
<!--tbody.appendChild(row_2);-->
<!--// Creating and adding data to third row of the table-->
<!--let row_3 = document.createElement('tr');-->
<!--let row_3_data_1 = document.createElement('td');-->
<!--row_3_data_1.innerHTML = "수지";-->
<!--let row_3_data_2 = document.createElement('td');-->
<!--row_3_data_2.innerHTML = "95";-->
<!--let row_3_data_3 = document.createElement('td');-->
<!--row_3_data_3.innerHTML = "94";-->
<!--let row_3_data_4 = document.createElement('td');-->
<!--row_3_data_4.innerHTML = "93";-->
<!--row_3.appendChild(row_3_data_1);-->
<!--row_3.appendChild(row_3_data_2);-->
<!--row_3.appendChild(row_3_data_3);-->
<!--row_3.appendChild(row_3_data_4);-->
<!--tbody.appendChild(row_3);-->
<!--</script>-->
<div id="sj"></div>
<script>
let th = ['이름','국어', '영어','수학'];
let sjdata = ['혜교', 99, 98,97 ];
let sj = document.getElementById('sj');
let table = document.createElement('table');
table.setAttribute('border', '1');
table.setAttribute('cellpadding', '10');
table.setAttribute('cellspacing', '0');
table.setAttribute('width', '500px');
//제목 행 작성
let tr = document.createElement('tr');
for (let val of th) {
let txtnode = document.createTextNode(val);
let th = document.createElement('th');
th.appendChild(txtnode);
tr.appendChild(th);
}
table.appendChild(tr);
// 본문 행 작성
tr= document.createElement('tr')
for (let val of sjdata) {
txtnode = document.createTextNode(val);
let td = document.createElement('td');
td.appendChild(txtnode);
tr.appendChild(td);
}
tr.setAttribute('align', 'center');
table.appendChild(tr);
sj.appendChild(table);
</script>
<h2>요소 내용 바꾸기</h2> <!-- 1회용 -->
<p>innerHTML : html 요소내에 마크업을 포함한 무언가를 삽입/수정/제거할때 사용 </p>
<p>textContent : 요소의 텍스트 컨텐츠를 가져오거나 변경할때 사용</p>
<span id="msg1"></span>
<span id="msg2"></span>
<p>게임목록</p>
<ul id = "games"></ul>
<script>
let msg1=document.getElementById('msg1');
let msg2=document.getElementById('msg2');
let games=document.getElementById('games');
msg1.innerHTML = '<p>Hello, World!!</p>'; //html컨텐츠 추가시
msg2.textContent = 'Hello, World!!';
games.innerHTML = '<li>디아블로</li>';
</script>
</body>
</html>