본문 바로가기

프로그래밍/React

자바스크립트로 DOM 조작하는 법

document로 DOM에 접근하는 법

document.getElementsByClassName: 클래스명으로 DOM에 접근

document.getElementById: id로 DOM에 접근

document.getElementsByTagName: 태그명으로 DOM에 접근

 

 

document에 DOM 요소 추가하는 법

요소는 만들기만 하면 DOM에 알아서 뿅 생기지 않습니다.

요소를 만들고, DOM에 넣어주어야 합니다.

 

document.createElement("만들 요소")

: 요소 만들기

 

document.만든 요소를 넣을 DOM 요소.appendChild(만든 요소를 담은 변수)

: 만든 요소 DOM에 넣기

// 새 요소를 만들어요.
const new_div = document.createElement("div");

// 한 눈에 확인해볼 수 있도록 스타일을 조금 추가해줄게요. 그냥 div는 눈에 안 보일테니까요!
new_div.style.backgroundColor = "green";
new_div.style.width = "100px";
new_div.style.height = "100px";

// 요소를 body에 추가해줍니다.
document.body.appendChild(new_div);

 

 

 

예제) 할 일(To-do)를 입력하면 박스 안에 입력한 내용을 출력하고,

완료하기 버튼을 누르면 박스 색깔이 바뀌게 하기

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8"/>
    <title>오늘의 투두</title>
</head>

<body>
<style>
    #title {
        color: blue;
        text-decoration: underline;
    }

    .wrap {
        display: flex;
        align-items: center;
    }

    .todo-card {
        border: 1px solid gray;
        border-radius: 5px;
        padding: 2em;
        margin: 1em;
        flex: 1 1 0;
    }

    button {
        width: 100px;
    }

    button:hover {
        background-color: orange;
    }
</style>

<h1 id="title">오늘 할 일</h1>

<div class="wrap">
    <div class="card-list">

    </div>

    <div class="add">
        <input id="add-input"/>
        <button onClick="addCard()">추가하기</button>
    </div>
</div>

<script>
    function completeTodo(e) { // 완료하기 함수
        e.target.parentElement.style.backgroundColor = "green"; // 배경색을 바꿔줍시다.
    }

    function addCard() { // 투두 카드를 추가하는 함수
        // 투두를 감싸는 div 만들고 클래스 이름을 줍니다.
        const new_todo = document.createElement("div");
        new_todo.className = "todo-card";

        // 투두 안에 들어갈 타이틀과 버튼을 만들어요.
        const title = document.createElement("h3");
        title.textContent = document.getElementById("add-input").value;
        const button = document.createElement("button");
        button.textContent = "완료";

        // 만든 버튼에 완료하기 함수를 연결해줘요.
        button.addEventListener("click", completeTodo);

        // 타이틀과 버튼을 투두에 추가해주고,
        new_todo.appendChild(title);
        new_todo.appendChild(button);

        // 목록에 투두를 추가해줘요.
        document.getElementsByClassName("card-list")[0].appendChild(new_todo);
    }
</script>
</body>