JS DOM과 이벤트 핸들링(2024-11-15 수업)

짝은별·2024년 11월 17일

JS

목록 보기
13/23

DOM 요소 생성하기

DOM노드를 만들기 위해 가장 간단한 방법은
createElement('tag')를 사용해 만들 수 있다

만약 이때 createTextNode()를 사용했다면 textNode를 생성할 수 있다

let span = document.createElement('span');
let text = document.createTextNode('안녕하세요');

node.명령어를 입력해 원하는 위치에 삽입하는 것도 가능하다
명령어의 종류는 다음과 같다

  • node.append(node or string) : 노드나 문자열을 node 끝에 삽입
  • node.prepend(node or string) : 노드나 문자열을 node 맨 앞에 삽입
  • node.after(node or string) : 노드나 문자열을 node 다음에 삽입
  • node.replace(node or string) : 노드를 새로운 노드나 문자열로 대체
const a = document.querySelector('.a') // span태그
const div = document.createElement('div');
const text = document.createTextNode('안녕하세요');
div.textContent = '안녕하세요'
// div.innerHTML을 이용하여 직접 text를 삽입해도 가능하다
a.append(div);

와 같이 사용한다

이는 react에서 주로 사용된다

insertAdjacent

insertAdjacentinsertAdjacentHTML, insertAdjacentText, 그리고 insertAdjacentElement가 존재한다

사용법은 insertAdjacentHTML('위치지정명령어' , tagName) 으로 사용된다
위치 지정 명령어는 다음과 같다

  • beforeend : elem바로 앞에 html을 삽입한다
  • afterbegin : elem의 첫번째 자식 요소 바로 앞에 html을 삽입
  • beforeend : elem의 마지막 자식 요소 바로 다음에 HTML을 삽입
  • afterend : elem의 마지막 자식 요소 바로 다음에 html을 삽입

insertAdjacentText는 문자를 그대로 삽입하고 insertAdjacentElement는 요소를 삽입한다

const a = document.querySelector('.a') // span태그
const div = document.createElement('div');
a.insertAdjacentHTML('beforeend' , div)

append와 비슷한 역할을 수행할 수 있다

노드 삭제 및 복사

node.remove()를 사용하여 삭제한다
만약 text만 비우고 싶다면 textContent = '' 를 사용하여 초기화 시키는 방법도 가능하다

const a = document.querySelector('.a'); // span태그
a.insertAdjacentHTML('beforeend' , `<div>안녕하세요</div>`);
a.remove();

이를 사용하면 a의 node가 삭제되어 내부에 있는 div 태그도 같이 삭제된다

cloneNode()를 이용하여 복제하는 것도 가능하다

const a = document.querySelector('.a') // span태그
a.insertAdjacentHTML('beforeend' , `<div>안녕하세요</div>`)

const b = a.cloneNode();

를 하게 되면 b에 a를 복사한다

이는 outerHTML을 사용하여 복사하는 경우도 있다

DocumentFragment

만약 여러 개의 tag를 묶어서 HTML에 삽입할 때 divspan같은 tag로 묶게 되면 div와 span사라지지 않아 작업이 복잡해질 수 있다
이때 사용하는 것이 DocumentFragment이다
사용법은 다음과 같다

let fragment = new DocumentFragment();

  for(let i=1; i<=3; i++) {
    let li = document.createElement('li');
    li.append(i);
    fragment.append(li);
  }

그러면 fragment의 결과는 다음과 같이 나타난다

<>
  <li>1</li>
  <li>2</li>
  <li>3</li>
<>

이를 HTML의 붙이는 순간 fragment(<>)사라지게 된다

CSS 디자인

전에 언급했언 css.style.prop과 같은 작업을 할 것이다
우선 css.style.prop로 지정하게 되면 CSS의 최상단의 위치하게 된다
따라서 이는 class를 다룰 수 없을 때 사용하는 것이 안전하다

이때 css.style.prop을 이용하여 CSS를 지정했을때 삭제하고 싶다면
css.stlye.prop = ''을 이용하여 초기화시킬 수 있다

이번엔 class를 할당하는 방법에 대해 살펴보자
전에 언급했던 setAttribute('class' , 'className')으로 class할당이 가능했다
하지만 문제하나의 class만 할당이 가능하다

따라서 여러 개의 class를 할당하기 위해선 classList를 사용하게 된다

  • classList.add : classList에 class 추가
  • classList.remove : classList에 class 제거
  • classList.toggle('className') : 만약 className이 존재할 경우 삭제하고 없다면 추가
  • classList.contains('className') : className이 있다면 true 없다면 false 반환

만약 여러 개의 CSS를 한 번에 적용시키고 싶다면 style.cssText를 이용하여 직접 적용시키는 방법이 있다
하지만 이는 값을 삭제하였다가 덮어씌우는 것이기에 주의해야한다

<div id="div">버튼</div>

<script>
  // cssText를 사용하면 'important' 같은 규칙도 설정할 수 있습니다.
  div.style.cssText=`color: red !important;
    background-color: yellow;
    width: 100px;
    text-align: center;
  `;

  alert(div.style.cssText);
</script>

이벤트

이벤트의 종류에는 여러가지가 있다
이벤트를 할당하기 위해선 addEventListener를 사용하여 이벤트를 줄 수 있다

이벤트의 종류는 다음과 같다

마우스 이벤트

  • click
  • contextmenu
  • mouseover
  • mouseout
  • mouseup
  • mousemove 등등

폼 요소 이벤트

  • submit
  • focus 등등

키보드 이벤트

  • keydown
  • keyup 등등

문서 이벤트

  • DOMContentLoaded

CSS 이벤트

-transitionend

이 외에도 다양한 이벤트들이 존재한다

만약 HTML 내부할당하려면 다음과 같이 할당 가능하다

<div onClick="console.log('hello')">HELLO 출력</div>

이때 div를 click하면 hello가 출력되는 이벤트가 할당된다

단 이런 방식으로는 하나의 event만 할당하기에 주의해야한다

addevntListener의 사용법은 다음과 같다

<div>HELLO 출력</div>
const div = document.querySelector('div');

function hello() {
  console.log('hello');
}

div.addEventListener('click' , hello);

addEventListener를 이용하면 하나의 값여러 개의 이벤트를 할당할 수 있다
이렇게 작성한 함수는 위의 HTML에 직접 준 방식과 같은 역할을 하게 된다

참고로 hello함수를 넣는 대신 그 안에 직접 함수를 작성해도 무방하다

div.addEventListener('click' , () => {
  console.log('hello');
}

하지만 함수를 분리하는 것이 가독성과 유지보수에 적절하다

만약 이벤트를 제거하고 싶다면 removeEventListener를 사용하면 된다

div.removeEventListener('click' , hello);

이벤트 객체

이벤트가 일어날때 우리는 어디서 어떻게 무슨 행동으로 일어났는지 모두 확인할 수 있다
이것은 이벤트 객체보관되기 때문이다

이벤트 객체는 이벤트가 생성만 되어도 생성된다

event.type,event.currentTarget, event.clientX, event.clientY등과 같이 사용된다

profile
FE(철 아님) 개발자 꿈꾸다

0개의 댓글