- Node
- DOM
- DOM CRUD & append & prepend
- Event 객체
- JSON
- localStorage
다음의 인터페이스들은 모두 Node로부터 메소드와 프로퍼티를 상속한다: Document, Element, CharacterData (Text, Comment, CDATASection이 상속), ProcessingInstruction, DocumentFragment, DocumentType, Notation, Entity, EntityReference
element - Node 의 차이
Node는 DOM 안의 어떤 타입의 객체든지 포함하는 포괄적 의미
Node.parentElement
Node.children
ParentNode.children
호출된 요소의 모든 자식 노드의 elements를 담고 실시간 HTMLCollection을 반환.
document.querySelector('#wikiArticle').children
//HTMLCollection(17) [p, p, h3, p, h3, pre.eval, p, p, h3, pre.line-numbers.language-html, pre.line-numbers.language-html, h3, p, p, h3, ul, p, .EC.9A.94.EC.95.BD: h3, .EA.B5.AC.EB.AC.B8.EA.B3.BC_.EA.B0.92: h3, .EC.98.88: h3, .EC.A3.BC.EC.9D.98: h3, .EB.AA.85.EC.84.B8: h3]
element.childNodes
주어진 요소의 자식 노드 모음을 반환
//NodeList(32) [p, p, text, h3, text, p, text, h3, text, pre.eval, text, p, text, p, text, h3, text, pre.line-numbers.language-html, text, pre.line-numbers.language-html, text, h3, text, p, text, p, text, h3, text, ul, text, p]
children 과 childNodes 의 차이
반환 값의 차이, HtmlCollection 과 NodeList를 각각 반환한다.
NodeList 값에는 textNode도 들어가 있다.
Node.cloneNode()
노드가 새로운 부모의 밑으로 붙기 전에 노드를 복제
cloneNode를 해도 자동으로 문서에 붙진 않음.
document.importNode()
다른 문서로 노드를 이동시킴.
DOM
Document Object Model
프로그래밍 언어가 웹사이트의 내용(content), 구조(structure) 그리고 스타일을 조작할 수 있게 만들어주는 인터페이스.
HTML CSS의 구조와 스타일을 파싱하기 위해, DOM이라 불리는 문서의 겉모양을 만들고, DOM 은 자바스크립트가 오브젝트로서의 웹사이트 문서의 컨텐츠, 엘리먼트에 접근할 수 있게 해준다.
DOM 과 자바스크립트의 차이
자바스크립트는 인터넷 브라우저 상의 DOM과 연결해주는 클라이언트 사이드 스크립팅 언어
DOM은 문서를 노드와 객체로 나타낸다
document 또는 window 요소에 대한 API를 사용해 문서 자체를 조작하거나 해당 하위 요소를 가져올 수 있다.
document 객체
웹사이트 접근, 수정할 수 있는 프로퍼티 또는 메소드를 가진 빌트인 오브젝트.
console.dir()
DOM 구조 조회
Create
createElement
Document.createDocumentFragment()
var element = document.getElementById('ul'); // assuming ul exists
var fragment = document.createDocumentFragment();
var browsers = ['Firefox', 'Chrome', 'Opera',
'Safari', 'Internet Explorer'];
browsers.forEach(function(browser) {
var li = document.createElement('li');
li.textContent = browser;
fragment.appendChild(li);
});
element.appendChild(fragment);
Read
document.querySelector
여러개 태그가 있을 경우, 첫번째 요소만 반환
querySelelctor 의 부모는 꼭 document가 아닌 element가 될 수 있다.
document.body.querySelector("style[type='text/css'], style:not([type])");
document.querySelectorAll
해당하는 태그 모두 반환. (유사배열 혹은 배열형 객체, array-like objects)
NodeList 반환. 배열은 아니지만 forEach()를 사용하여 반복할 수 있다. 또한 Array.from()을 사용하여 Array로 변환할 수 있다.
NodeList 에 forEach 메소드는 존재하나, reduce와 같은 array 메소드는 포함되지 않고 있다.
Array.from()
메서드는 유사 배열 객체(array-like object)나반복 가능한 객체(iterable object)를 얕게 복사해새로운Array 객체를 만든다.
Array.from(arrayLike[, mapFn[, thisArg]])
- arrayLike 배열로 바꾸고 싶은 유사 배열 객체나 반복 가능 객체.
- mapFn 모든 요소에 호출할 맵핑 함수
- thisArg 맵핑시 this로 사용할 값
```jsx
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
```
document.querySelectorAll()은 정적 NodeList를 반환한다.
NodeList 객체
일반적으로 element.childNodes와 같은 속성과 document.querySelectorAll과 같은 메서드에 의해 반환되는 노드 콜렉션
다른 경우 NodeList는 정적 콜렉션
DOM 을 변경해도 콜렉션 내용에는 영향을 주지 않는다.
getElementById
getElementsByTagName
getElementsByClassName
Update
textContent, id, classList, setAttribute
textContent, innerHTML, innerText 차이
<div id='blog test'>
This element is <strong>strong</strong> and has some super fun <code>code</code>!
</div>
//render
const getValue = document.getElementById('blog-test');
console.log(getValue.innerHTML);
// => This element is <strong>strong</strong> and has some super fun <code>code</code>!
console.log(getValue.innerText);
// => This element is strong and has some super fun code!
console.log(getValue.textContent);
// => This element is strong and has some super fun code!
classList
Element.classList.add()
setAtrribute()
추가할 땐 setAtrribute, 삭제시 removeAttribute, 조회시 getAttribute를 사용.
Delete
remove, removeChild, innerHTML = "", textContent=""
innerHTML은 여러 보안상 문제를 갖고 있다.
removeChild
자식 엘리먼트를 지정하여 삭제
Append
Node.appendChild()
메소드는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙인다. 만약 주어진 노드를 참조하고 있다면 현재 위치에서 새로운 위치로 이동시킨다.
https://indepth.dev/here-is-why-appendchild-moves-a-dom-node-between-parents/
// 새로운 단락 요소를 생성하고 문서에 있는 바디 요소의 끝에 붙입니다.
var p = document.createElement("p");
document.body.appendChild(p);
append
ParentNode.append()
ParentNode의 마지막 자식 뒤에 Node 객체 또는 DOMString 객체를 삽입한다.
appendChild와 append 차이점.
append는 DOMString도 추가 가능
append 는 반환하는 값이 없다. appendChild는 추가한 Node 객체를 반환
append는 여러 노드와 문자를 추가할 수 있다.
//텍스트 추가
var parent = document.createElement("div");
parent.append("Some text");
console.log(parent.textContent); // "Some text"
//요소와 문자 추가
var parent = document.createElement("div");
var p = document.createElement("p");
parent.append("Some text", p);
console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
Prepend
for ... of문
for...of 명령문은 반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"
script 실행 위치
event 객체
사용자 입력 등의 트리거에 의해 발생한 이벤트 정보가 담긴 객
- onsubmit
- onchange
- onmouseover
- onkeyup
- event.preventDafault
- onclick
- addEventListener와의 차이
JSON
Javascript Object Notation
JSON을가지고 html 변환 작업
JSON.stringify()
JSON.parse()
localStorage
- .setItem()
- .getItem()
- .removeItem()
- .clear()
@@ 오늘은 페어 프로그래밍 트위터 페이지 2번째 시간이자 기능 구현 첫 번째 시간을 가졌다. 알고리즘 개별 문제를 풀때와는 좀 더 다른 느낌이었다. 아무래도 유닛테스트로 짜여진 그리고 입력과 출력이 주어졌던 알고리즘 문제와는 달리 어느정도의 가이드는 있었지만 함수를 구성하고 구현하는 것에 자유도가 더해지다보니 쉬운 문제도 어렵게 느껴지기도 하고.....
그래도 그 안에서 새롭게 알게 되는 것이 많았다.
아무래도 익숙지 않다보니 계속 콘솔을 찍어가며 확인했고, 생각보다 조금 더 시간이 많이 걸렸다. 그래도 필터링 함수를 제외하고 나머지는 어느정도 구현된 상태다. Advanced 이긴 하지만 로컬 저장소도 이용해보고 싶고, Date 객체로 뽑아낸 등록 시간도 좀더 사용자 친화적으로 바꾼다는 게 어떤 로직일까 머릿속으로 상상이 잘 안간다.
내일 제 시간안에 마무리 지을 수 있을지 모르겠지만 시간이 된다면 끝까지 완주해봐야지.
그리고 오늘, 개인적으로는 DOM 을 다시 복습하는 시간을 가졌다. 객체, 배열 메소드에 비하면 DOM 조작 메소드들은 뭔가 더 까다롭고 복잡한 느낌이다.
파라미터도 많고, 어느정도 메소드 이름에서 규칙성을 유추할 수 있었다면 좀더 mdn 문서를 꼼꼼하게 읽어야하는 느낌이고, 비슷한 이름의 메소드들이 많아서 꽤 헷갈린다.
계속 찾아보고 써보고 몸으로 체득하는 수 밖에 없을 것 같다. 오늘은 날 때문에 지치고 뭔가 계속 지치는 하루였는데, 그래도 계획하는 바를 3분의 1정도는 끝내서 뿌듯하다 (아직도 내 to do list는 처리 못한 게 가득하지만..) 조바심 내지 말고 한개씩 차분하게 마무리 지어 가야겠다.