TIL.11_CRUD part1.

Ryan Lee·2021년 4월 26일
0

Today I Learned!

목록 보기
11/11
post-thumbnail

Create

  • createElement
const createDiv = document.createElement('div')

새로운 element를 만들때는 보통 createElement를 사용한다.



  • createDocumentFragment
let fragment = document.createDocumentFragment()

:: 가상 document 객체를 만들어 사용할 수 있다.

let hogwarts = document.createElement("div");
hogwarts.textContent = "Hogwarts";

let fragment = document.createDocumentFragment(); // 가상 document 생성

fragment.appendChild(hogwarts); // 가상 document에 hogwarts element 붙임

document.body.appendChild(fragment); // 진짜 document에 가상 document 붙임.

브라우저 화면은...

const list = document.getElementById("list");
const fragment = document.createDocumentFragment();
let el, text;

["HarryPotter", "HermioneGranger", "RonWeasley"].forEach(function (user) {
  el = document.createElement("li");
  text = document.createTextNode(user);
  el.appendChild(text);
  fragment.appendChild(el);
});

list.appendChild(fragment);

화면에는...


append vs appendChild

  1. append는 node 객체뿐만 아니라 dom string도 추가 가능하나, appendChild는 오직 node객체만 추가할 수 있습니다.
const parent = document.createElement("div");
const child = document.createElement("span");

parent.append(child);  // node 객체 추가 가능
parent.append("append는 문자열도 추가됩니다.");  // string 추가 가능

const parent = document.createElement("div");
const child = document.createElement("span");

parent.appendChild(child);   // node 객체 추가 가능

parent.appendChild("appendChild는 문자열 에러납니다.");  // 아래와 같은 오류발생!



  1. append 는 반환하는 값이 존재하지 않는데 비해 appendChild는 추가한 node 객체를 반환한다.
const parent = document.createElement("div");
const child = document.createElement("span");

const appendValue = parent.append(child);
console.log(appendValue);     // undefined

const appendChildValue = parent.appendChild(child);
console.log(appendChildValue);   // <span></span>


  1. append는 여러개의 node와 string을 동시에 추가할 수 있으나, appendChild는 한가지만 추가할 수 있다.
const parent = document.createElement("div");
const tag1 = document.createElement("p");
const tag2 = document.createElement("p");

parent.append(tag1, tag2, "javascript"); 
// <p></p><p></p>"javascripts" 모든게 다 추가된다.

parent.appendChild(tag1, tag2, "javascript"); 
//  <p></p>  첫번째 tag1만 추가된다.
  • append

  • appendChild


같은 엘리먼트를 appendChild하면 복사? 이동?


같은 엘리먼트에서 appendChild하면 이동한다.
  • 아래와 같이 html을 작성하면
<div class="a">
      여기는 클래스A
      <span>나는 어디로 갈까요?</span>
    </div>
    <div class="b">여기는 클래스B</div>
  • 화면에는 다음과 같이 나온다.

  • 다음과 같이 appendChild를 사용하여
const spanMovement = document.querySelector("span");
const classB = document.querySelector(".b");  
classB.appendChild(spanMovement);  // span을 같은 엘리먼트에 붙여넣으면 복사가 아닌 이동한다.

profile
📡 Gryffindor :) programmer

0개의 댓글