[JS]How the DOM really works, Selecting, Creating, and Deleting elements, Styles, Attributes and Classes

Hyodduru ·2021년 12월 22일
0

JavaScript

목록 보기
45/60
post-thumbnail

강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)

How the DOM Really Works

Review : What is DOM?

  • Allow us to make JS interact with the browser
  • We can write JS to create, modify and delete HTML elements, set styles, classes and attributes, and listen and respond to events
  • DOM tree is generated from an HTML document, which we can them interact with
  • DOM is a very complex API(Application Programming Interface) that contains lots of methods and properties to interact with the DOM tree ex) .querySelector(), .addEventListener(), .createElement(), .innerHTML, .textContext, .children, etc ....

How the DOM API organized behind the scenes

Event Target ex)addEventListener(), .removeEventListner()

  • window : Global Object. lots of methods and properties.
  • node : 모든 DOM tree 요소들의 type은 node이다. ex) .textContext, .childNodes, .parentNode, .cloneNode()
    • Element : 여러 method를 이용하여 HTML에 접근 가능. HTMLElement에서도 HTML ButtonElement, HTML Div Element등으로 나뉘어짐.
      • ex) .innerHTML, .classList, .children, .parent Element, .append(), .remove(), .insertAdjacentHTML(), .querySelector(), .closest(), .matches(), .scrollIntoView(), .setAttribute()
    • text : < p > paragraph < p >
    • Comment : <!-- comment -- >
    • Document : 또 다른 형태의 node.
      • ex) .querySelector(), .createElement(), .getElementbyId()

유의할 점!
Inheritance of methods and properties
모든 종류의 node들은 node와 event target의 method와 properties를 이용할 수 있다.
ex) Any HTML Element will have access to .addEventListener(), . cloneNode() or .closest()methods.

Selecting,Creating, and Deleting Elements

Selecting Elements

console.log(document.documentElement);
console.log(document.head);
console.log(document.body);

const header = document.querySelector('.header');
const allSections = document.querySelectorAll('.section');
console.log(allSections);
//NodeList(4) [section#section--1.section, section#section--2.section, 
section#section--3.section, section.section.section--sign-up]
// DOM 변화 자동적으로 수정되지 않음!
document.getElementById('section--1');
const allButtons = document.getElementsByTagName('button');
console.log(allButtons);
//HTMLCollection(9) [button.btn--text.btn--scroll-to, 
button.btn.operations__tab.operations__tab--1.operations__tab--active, 
button.btn.operations__tab.operations__tab--2, button.btn.operations__tab.operations__tab--3, 
button.slider__btn.slider__btn--left, button.slider__btn.slider__btn--right, button.btn.btn--
show-modal, button.btn--close-modal, button.btn]
// HTMLColloection을 live object라고도 함. DOM 이 수정되면 HTMLColloection 또한 자동적으로 바뀐다.

console.log(document.getElementsByClassName('btn'));
// return HTMLCollection

Creating and inserting elements

.insertAdjacentHTML

createElement, prepend, append, before, after

const message = document.createElement('div');
message.classList.add('cookie-message');
// message.textContent = 'We use cookies for improved functionality and analytis.';
message.innerHTML =
  'We use cookies for improved functionality and analytis. <button class ="btn btn--close-cookie">Got it!</button>';

//header.prepend(message); // prepend : 해당 element의 first child에 insert한다!
header.append(message); // append : last child
// 한 번에 한 곳만 insert됌

// header.append(message.cloneNode(true)); cloneNode -> 메서드를 호출한 Node 의 복제된 Node를 반환. 위아래 다 insert 가능

//header.before(message); // 호출한 node 전에 insert 한다.
//header.after(message); // 호출한 node 뒤에 insert 한다.

Delete elements

document.querySelector('.btn--close-cookie').addEventListener('click', () => {
  message.remove();
  //message.parentElement.removeChild(message);
});

Styles, Attributes and Classes

Styles

message.style.backgroundColor = '#37383d';
message.style.width = '120%';

console.log(message.style.height); // 확인 불가. 우리가 직접 style property를 이용해서 설정한 것들만 확인 가능. (only inline property)
console.log(message.style.width); //120%

console.log(getComputedStyle(message).color); // rgb(187, 187, 187)  getComputedStyle : 모든 style property -value 들어있음.
console.log(getComputedStyle(message).height); //50px

message.style.height =
  Number.parseFloat(getComputedStyle(message).height, 10) + 30 + 'px';

change css custom properties - setProperty

document.documentElement.style.setProperty('--color-primary', 'orangered');

Attributes

standard property 만 읽을 수 있다. ex) img.designer 읽을 수 없음

const logo = document.querySelector('.nav__logo');
console.log(logo.alt); //Bankist logo

console.log(logo.className); //nav__logo

logo.alt = 'Beautiful minimalist logo';

//Non standard
console.log(logo.designer); //undefined
console.log(logo.getAttribute('designer')); //Jonas
logo.setAttribute('company', 'Bankist');

//src
console.log(logo.src); //http://127.0.0.1:5500/img/logo.png (absolute version)
console.log(logo.getAttribute('src')); //img/logo.png (relative version)

const link = document.querySelector('.nav__link--btn');
console.log(link.href); //http://127.0.0.1:5500/index.html#
console.log(link.getAttribute('href')); //#

Data attributes

console.log(logo.dataset.versionNumber); //3.0

Classes

logo.classList.add('c', 'j');
logo.classList.remove('c', 'j');
logo.classList.toggle('c');
logo.classList.contains('c');

//Don't use
// logo.className = 'jonas'; // 기존의 모든 className을 override 한다.

profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글