본문 바로가기
웹 퍼블리싱 자료집/JavaScript

[JavaScript] DOM

by cogito30 2025. 3. 6.
반응형

script 연결

- script 태그 이용. defer를 사용하여 HTML 페이지 로딩을 동시에 진행

- script 위치 순서 중요

더보기
<!-- HTML 파일에 JavaScript 파일 연동 -->
<script defer src="index.js"></script>

<!-- HTML에 JavaScript 이용 -->
<script>
  console.log("Hello, Javascript!");
</script>

출력

더보기
// console 창에 출력
console.log("Hello World!");

// pop업 창으로 확인 메시지
alert("Are You Ready?");

HTML 요소 선택

더보기
// 선택자로 HTML 요소 1개 선택
const tag = document.querySelector("선택자");

// 선택자로 HTML 요소 모두 선택
const tagList = document.querySelectorAll("선택자");

// 자식들 모두 선택
const div = document.querySelector("div");
const child = div.children;

// 직계 부모 탐색
const div = document.querySelector("div");
const parent = div.parentElement;

// 조상 탐색
const div = document.querySelector("div");
const ancestor = document.closet("선택자");

// 형제 탐색(이전, 다음)
const div = document.querySelector("div");
const prevSib = div.previousElementSibling;
const nextSib = div.nextElementSibling;

스타일 제어

더보기
/* inline style로 추가. 값은 문자열 사용 */
// width 너비 설정
dom요소.style.width = "20px"; 

// 배경 설정. 하이픈(-) 대신 camelCase이용
dom요소.style.backgroundColor = "blue";

// tranform 설정
dom요소.style.transform = "rotate(10deg)";

// border 설정
dom요소.style.border = "none";

이벤트 연결

더보기
/* 이벤트 등록 */
dom요소.addEventListener(이벤트명, 함수);

// ES5 function 함수 사용 예시
dom요소.addEventListener("click", function() {
    this.style.color = "blue";
});

// ES6(ECMAScript 2015) 화살표 함수 사용 예시
dom요소.addEventListener("click", (e) ={
    e.preventDefault();
    e.currentTarget.style.backgroundColor = "red"; // 현재 요소 배경 설정
    e.currentTarget.innerHTML = "New Text";    // 현재 요소 텍스트 설정
    ...
});

HTML Class 설정

더보기
dom요소.classList.add("class명");       // html 요소에 class명 추가
dom요소.classList.remove("class명");    // html 요소에 class명 제거
dom요소.classList.contains("class명");  // 포함될 경우 true 반환, 없는 경우 false 반환

이벤트 연결 예시(마우스 hover)

더보기

(index.html)

<body>
  <div id="box"></div>
</body>

(index.js)

const box = document.querySelector("#box");

box.addEventListener("mouseenter", () => {
  box.style.backgroundColor = "blue";
});

box.addEventListener("mouseleave", (e) => {
  e.currentTarget.style.backgroundColor = "aqua";
});

/* ES5 예시 */
box.addEventListener("mouseenter", function() {
  this.style.backgroundColor = "blue";
});

box.addEventListener("mouseleave", function() {
  this.style.backgroundColor = "aqua";
});

이벤트 연결 예시(카운터)

더보기

(index.html)

<body>
  <div>
    <p class="num">0</p>
    
    <button class="plus">plus</button>
    <button class="minus">minus</button>
  </div>
</body>

(index.js)

const num = document.querySelector(".num");
const plus = document.querySelector(".plus");
const minus = document.querySelector(".minus");
let cnt = parseInt(num.innerText, 10);

plus.addEventListener("click", () => {
  cnt++;
  num.innerText = cnt;
});

minus.addEventListener("click", () => {
  cnt--;
  num.innerText = cnt;
});

박스 회전

더보기

(index.html)

<body>
  <button class="left">반시계 방향 회전</button>
  <button class="right">시계 방향 회전</button>

  <div class="wrap">
    <div class="rect"> </div>
  </div>
</body>

(style.css)

.wrap .rect {
    width: 300px;
    height: 300px;
    margin: 50px;
    background: blue;
    transition: 0.5s;
}

(index.js)

const btnLeft = document.querySelector(".left");
const btnRight = document.querySelector(".right");
const rect = document.querySelector(".rect");
const deg = 45;
let cnt = 0;

btnLeft.addEventListener("click", (e) => {
  cnt--;
  rect.style.transform = `rotate(${cnt*deg}deg)`;
  console.log(cnt);
});

btnRight.addEventListener("click", (e) => {
  cnt++;
  rect.style.transform = `rotate(${cnt*deg}deg)`;
  console.log(cnt);
});

HTML Class 속성으로 CSS 제어 예시

더보기

(index.html)

<body>
  <div class="wrap">
    <div class="rect"></div>
  </div>
</body>

(style.css)

@charset "UTF-8";

.wrap {
  width: 500px;
  height: 500px;
  border: 1px solid #000;
  padding: 100px;
  box-sizing: border-box;
  margin: 100px auto;
}

.wrap .rect {
  width: 100%;
  height: 100%;
  background: aqua;
  transition: 1s;
}

.wrap .rect.on {
  background: orange;
}

(index.js)

const wrap = document.querySelector(".wrap");
const rect = wrap.querySelector(".rect");

rect.addEventListener("click", () => {
  let isOn = rect.classList.contains("on");
  
  if(isOn) {
    rect.classList.remove("on");
  } else {
    rect.classList.add("on");
  }
  
  // 삼항 연산자 사용
  (isOn) ? rect.classList.remove("on") : rect.classList.add("on");
  
  // toggle로 조건문 대체
  rect.classList.toggle("on");
});

코드 패키징 예시

더보기

(index.html)

<body>
  <ul class="btns">
    <li class="on">button1</li>
    <li>button2</li>
    <li>button3</li>
  </ul>
  
  <section>
    <article class="on">Box1</article>
    <article>Box2</article>
    <article>Box3</article>
  </section>
</body>

(style.css)

@charset "UTF-8";

ul li {
  color: gray;
  cursor: pointer;
}

ul li.on {
    color: black;
}

section {
  width: 300px;
  height: 200px;
  border: 1px solid #888;
  margin: 50px;
  position: relative;
  perspective: 600px;
}

section article {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 50px;
    opacity: 0;
    transform: rotateY(-180deg);
    transition: 0.5s;
}

section article.on {
    opacity: 1;
    transform: rotateY(0deg);
}

section article:nth-of-type(1){
    background: aqua;
}
section article:nth-of-type(2){
    background: pink;
}
section article:nth-of-type(3){
    background: orange;
}

(index.js)

const btns = document.querySelectorAll(".btns li");
const boxs = document.querySelectorAll("section article");

for (let i=0; i < btns.length; ++i) {
    btns[i].addEventListener("click", (e) => {
        activation(i, btns);
    });
}

function activation(index, list) {
    for (let el of list) {
        el.classList.remove("on");
    }
    list[index].classList.add("on");
}
반응형