DOM으로 HTML 작성하기 기초

2021. 8. 21. 13:00
반응형

DOM(Document Object Model)로 HTML을 조작하지 않고 문서를 작성해보려 한다.

 

과일 데이터를 입력받아 DOM으로 HTML에 리스트화를 해볼 것이다.

 

우선 기본 HTML틀만 만들어 놓고 시작해보자. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fruit List</title>
<link rel="stylesheet" href="fruits.css"> //나중에 리스트를 보기좋게 바꾸어 줄 것이다.
</head>
<body>
    <ul class="fruits">
        
    </ul>
<script src="fruits.js"></script> //따로 js파일을 연결시켜 js만 따로 작성할 것이다.
</body>
</html>
cs

 

그리고 아래와 같은 자료가 있다고 가정해보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const fruits = [
    {
        id : 1,
        name : '사과',
        price : '1,000원',
        quantityLeft : '200 개',
        DeliveryAvailable : '가능'
    },
    {
        id : 2,
        name : '배',
        price : '1,200원',
        quantityLeft : '250 개',
        DeliveryAvailable : '가능'
    },
    {
        id : 3,
        name : '바나나',
        price : '2,900원',
        quantityLeft : '180 개',
        DeliveryAvailable : '불가'
    },
    {
        id : 4,
        name : '수박',
        price : '1,8000원',
        quantityLeft : '80 개',
        DeliveryAvailable : '가능'
    },
    {
        id : 5,
        name : '토마토',
        price : '800원',
        quantityLeft : '270 개',
        DeliveryAvailable : '가능'
    },
    {
        id : 6,
        name : '복숭아',
        price : '2,700원',
        quantityLeft : '480 개',
        DeliveryAvailable : '가능'
    },
    {
        id : 7,
        name : '오렌지',
        price : '1,100원',
        quantityLeft : '170 개',
        DeliveryAvailable : '불가'
    },
    {
        id : 8,
        name : '참외',
        price : '1,300원',
        quantityLeft : '210 개',
        DeliveryAvailable : '가능'
    },
    {
        id : 9,
        name : '자몽',
        price : '2,000원',
        quantityLeft : '200 개',
        DeliveryAvailable : '불가'
    },
    {
        id : 10,
        name : '레몬',
        price : '1,000원',
        quantityLeft : '320 개',
        DeliveryAvailable : '가능'
    }
]
cs

 

이제 이 자료들을 리스트화 해볼 것이다.

 

그리고 과일의 이름을 클릭하면 배송가능 여부가 나오도록 만들어 보자.

 

그럼 먼저, 틀을 구성해보자.

 

자료의 갯수만큼 만들어 줘야하니까 for문을 사용할 것이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function fruitList (arr) {
    for(let i = 0; i < fruits.length; i++){
        const ul = document.querySelector(".fruits");
        const li = document.createElement('li');
        const name = document.createElement('a');
        const price = document.createElement('span');
        const quantityLeft = document.createElement('span');
        ul.appendChild(li);
        li.appendChild(name);
        li.appendChild(price);
        li.appendChild(quantityLeft);
    }   
}
cs

 

li태그를 생성하고 이어서 a, span태그를 생성 해준다. 그리고 li는 ul자식태그로, a와 span은 li의 자식태그로 넣어준다.

이렇게 까지만 해놓고 개발자 도구를 보면

 

 

 

 

 

 

 

 

 이런식으로 10개의 li태그와 그 안에 <a>, <span> 태그가 들어간것을 볼 수 있다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

여기까지 했다면 이제 자료에 있는 값을 태그안에 입력해서 html 화면에 띄워보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function fruitList (arr) {
    for(let i = 0; i < fruits.length; i++){
        const ul = document.querySelector(".fruits");
        const li = document.createElement('li');
        const name = document.createElement('a');
        const price = document.createElement('span');
        const quantityLeft = document.createElement('span');
        ul.appendChild(li);
        li.appendChild(name);
        li.appendChild(price);
        li.appendChild(quantityLeft);
        name.textContent = `과일명 : ${fruits[i].name}`;
        price.textContent = `개당 가격 : ${fruits[i].price}`;
        quantityLeft.textContent = `남은 수량 : ${fruits[i].quantityLeft}`;
    }   
}
fruitList(fruits);
cs

 

 

textContent를 사용해서 태그안에 자료를 작성해준다. 위 처럼 작성해주면 아래와 같은 결과가 나온다.

 

 

이렇게 나오면 보기가 싫으니까 아까 연결해 두었던 css에서 조금 만져주자.

 

우선 css로 바꿔주기 위해서는 클래스를 추가해 주어야 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function fruitList (arr) {
    for(let i = 0; i < fruits.length; i++){
        const ul = document.querySelector(".fruits");
        const li = document.createElement('li');
        const name = document.createElement('a');
        const price = document.createElement('span');
        const quantityLeft = document.createElement('span');
        ul.appendChild(li);
        li.appendChild(name);
        li.appendChild(price);
        li.appendChild(quantityLeft);
        name.textContent = `과일명 : ${fruits[i].name}`;
        price.textContent = `개당 가격 : ${fruits[i].price}`;
        quantityLeft.textContent = `남은 수량 : ${fruits[i].quantityLeft}`;
        li.classList.add('list'//클래스 추가
        name.classList.add('name'); //클래스 추가
    }   
}
fruitList(fruits);
cs

 

 

CSS는 아래와 같이 만들어 주었다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.list {
  display: flex;
  flex-direction: column;
  padding: 1rem;
}
.name {
  font-weight: bold;
}
 
cs

 

 

이렇게 해준 결과!

 

 

나름 깔끔하게 보이도록 만들어 졌다. 그럼 이제 과일명을 클릭하면 콘솔에 배달가능 여부가 나오도록 해보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function fruitList (arr) {
    for(let i = 0; i < fruits.length; i++){
        const ul = document.querySelector(".fruits");
        const li = document.createElement('li');
        const name = document.createElement('a');
        const price = document.createElement('span');
        const quantityLeft = document.createElement('span');
        ul.appendChild(li);
        li.appendChild(name);
        li.appendChild(price);
        li.appendChild(quantityLeft);
        name.textContent = `과일명 : ${fruits[i].name}`;
        price.textContent = `개당 가격 : ${fruits[i].price}`;
        quantityLeft.textContent = `남은 수량 : ${fruits[i].quantityLeft}`;
        li.classList.add('list')
        name.classList.add('name');
        name.onclick = function () { // onclick 메소드 사용
            printDeliveryAvailable(arr[i]); // 아래에 만든 함수를 불러온다.
        }
    }   
}
fruitList(fruits);
 
function printDeliveryAvailable (fruit) {
    console.log(`${fruit.name} 배송가능 여부 : ${fruit.DeliveryAvailable}`);
}
 
cs

 

onclick 메소드를 이용해서 아래에 만든 함수를 불러오게 만든다. 이렇게 해주면 아래에 보이는 것 처럼 과일명을 클릭했을 때 콘솔창에

배송가능 여부가 찍히게 된다.

 

 

이로써 DOM을 활용한 HTML 작성하기 기초를 마치도록 하겠다.

반응형
LIST

'학습 TIL > HTML' 카테고리의 다른 글

HTML 기초  (0) 2021.08.01

BELATED ARTICLES

more