dev-story
[JavaScript] #08_ DOM 본문
DOM(Document Object Model)
Node객체
텍스트가 있는 노드 생성
(노드=태그(태그를 객체화 시켜서 보는 것))
document.createElement('태그명') :해당 태그명의 요소를 만들겠다.
document.createTextNode() :요소안에 텍스트 노드 넣음
appendChild() :자식으로써 이어붙임. 태그안에다 붙여넣겠다.
<button onclick='test1();'>실행확인</button>
<div id='area1' class='area'></div>
<script>
function test1(){
var title = document.createElement('h3'); //<h3></h3>
var textNode = document.createTextNode('안녕');
title.appendChild(textNode); //<h3>안녕</h3>
document.getElementById('area1').appendChild(title);
}
</script>
텍스트가 없는 노드 생성
대표적으로 이미지.
.src=사진경로 속성 추가
.width = 크기 지정 속성 추가
.height = 크기(높이)지정 속성 추가
<button onclick='test2();'>실행확인</button>
<div id='area2' class='area'></div>
<script>
function test2(){
var imgTest = document.createElement('img');
imgTest.src='https://www.telegraph.co.uk/content/dam/Pets/spark/royal-canin/happy-puppy.jpg?imwidth=1240';
imgTest.width = '150';
imgTest.height = '100';
document.getElementById('area2').appendChild(imgTest);
}
</script>
없는 속성을 넣고 싶을때
.setAttribute(속성이름, 값)
innerHTML
: 안에 작성한 태그들을 HTML로 인지
<button onclick='test3();'>실행확인</button>
<table id='board'>
<tr>
<th>글 번호</th>
<th>글 제목</th>
<th>작성자</th>
<th>조회수</th>
<th>작성일자</th>
</tr>
</table>
<script>
function test3(){
var board = document.getElementById('board');
var num = 1;
var title = '제목임다';
var user = 'user01';
var count = 1;
var date = new Date();
board.innerHTML += '<tr><td>' + num + '</td>'
+ '<td>' + title + '</td>'
+ '<td>' + user + '</td>'
+ '<td>' + count + '</td>'
+ '<td>' + date.getFullYear() + "-" + (date.getMonth()+1)
+ "-" + date.getDate() + "</td></tr>";
}
</script>
버튼을 누를때마다 작성한 값이 표안에 작성됨.

innerText
안에 작성한 내용을 글자로만 인식.
위 코드에서 innerHTML을 innerText로 바꾸면

스타일 지정
<button onclick='test4()'>실행확인</button>
<div id='area4' class='area'></div>
<script>
function test4(){
var area4 = document.getElementById('area4');
area4.style.backgroundColor = 'black';
area4.style.borderRadius = '100px';
area4.style.transition = 'all 2s'; //모든 걸 2초안에 끝내라.
}
노드 삭제
.remove()
<button onclick='test5();'>실행확인</button>
<div id='area5' class='area'></div>
<script>
function test5(){
var area5 = document.getElementById('area5');
area5.remove();
}
728x90
'[프론트엔드] > JavaScript' 카테고리의 다른 글
| [JavaScript] #10_ 정규표현식 (0) | 2022.04.17 |
|---|---|
| [JavaScript] #09_ Event (0) | 2022.04.14 |
| [JavaScript] #07_ BOM (0) | 2022.04.14 |
| [JavaScript] #06_ window객체 (0) | 2022.04.14 |
| [JavaScript] #05_ 객체(Object) (0) | 2022.04.14 |
Comments