12월 24일 복기

Ji Taek Lim·2020년 12월 24일

double for loop javascript
https://stackoverflow.com/questions/37103946/double-for-loop-in-javascript

루프와 반복
https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Loops_and_iteration

아 readVertically 하다가 머리에 쥐나는 줄 알았다. 계속 쥐날 예정.. 푸는 방법을 알아야겠다.

오늘은 HTML 유효성 검사를 한다. 어제에 이어서 공부를 한다.

Document.querySelector()

UPDATE - textContent, classList.add


const oneDiv = document.createElement('div')
console.log(oneDiv) // <div></div>

oneDiv.textContent = 'dev';
console.log(oneDiv) // <div>dev</div>

oneDiv.classList.add('tweet')
console.log(oneDiv) // <div class="tweet">dev</div>

const container = document.querySelector('#container')
container.append(oneDiv)

setAttribute

textContent와 innerHTML의 차이
(difference between textContent and innerHTML)

innerHTML의 보안상 단점 (mdn innerHTML security issue)

DELETE - remove, removeChild


const container = document.querySelector('#container')
const tweetDiv = document.createElement('div')
container.append(tweetDiv)
tweetDiv.remove() // 이렇게 append 했던 엘리먼트를 삭제할 수 있다.
모든 자식 지우기
document.querySelector('#container').innerHTML = '';
const container = document.querySelector('#container');
while (container.firstChild) {
  container.removeChild(container.firstChild);
}
const tweets = document.querySelectorAll('.tweet')
tweets.forEach(function(tweet){
    tweet.remove();
})
// or
for (let tweet of tweets){
    tweet.remove()
}

element와 node의 차이

element

https://developer.mozilla.org/ko/docs/Web/API/Element

mdn

https://developer.mozilla.org/ko/docs/Web/API/Node

difference between element and node in javascript dom

A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document or document.body, it could be an HTML tag specified in the HTML such as or

or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node is any DOM object.

An element is one specific type of node as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).

The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document node would have its list of child nodes (the head node and the body node). The body node would have its list of child nodes (the top level elements in your HTML page) and so on.

So, a nodeList is simply an array-like list of nodes.

An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id or a class. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):

You can see an ELEMENT_NODE is one particular type of node where the nodeType property has a value of 1.

So document.getElementById("test") can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.

Since document.getElementsByClassName("para") can return more than one object, the designers chose to return a nodeList because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList, but they chose to use just one type of collection whether it had only elements in it or not.

아 이거 진짜 무슨말이냐 힘드네... 이따가 다시 한번 해석해보자..

tweets에 forEach는 되는데, reduce는 안되는 이유

https://stackoverflow.com/questions/31338097/why-it-is-not-possible-to-call-foreach-on-a-nodelist

Although NodeList is not an Array, it is possible to iterate on it using forEach(). It can also be converted to an Array using Array.from().

However some older browsers have not yet implemented NodeList.forEach() nor Array.from(). But those limitations can be circumvented by using Array.prototype.forEach() (more in this document).

Answer

[].forEach returns a function - this a not so clever shortcut for Array.prototype.forEach

Boom

tweets를 유사 배열에서 배열로 바꾸는 방법

https://attacomsian.com/blog/javascript-convert-nodelist-to-array

A NodeList is an array-like object that represents a collection of DOM elements or more specifically nodes. It is just like an array, but you can not use the common array methods like map(), slice(), and filter() on a NodeList object.

[...] a NodeList is a collection of nodes that can be used to access and manipulate DOM elements, while an array is a JavaScript object which can hold more than one value at a time.

Both NodeLists and arrays have their own prototypes, methods, and properties. You can easily convert a NodeList to an array if you want to, but not the other way around.

(1) Array.from() Method

// create a `NodeList` object
const divs = document.querySelectorAll('div');

// convert `NodeList` to an array
const divsArr = Array.from(divs);

(2) Spread Operator

// create a `NodeList` object
const divs = document.querySelectorAll('div');

// convert `NodeList` to an array
const divsArr = [...divs];

(3) Array.prototype.slice() Method

// create a `NodeList` object
const divs = document.querySelectorAll('div');

// convert `NodeList` to an array
const divsArr = Array.prototype.slice.call(divs);


const divsArr = [].slice.call(divs);

HTML에 자바스크립트 적용하기

HTML에서 Javascript 파일을 불러올 때 주의점에 대해서 이해할 수 있다.
script 태그가 적용되는 위치에 따라서 실행 결과가 달라질 수 있음을 이해할 수 있다.

  <!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="myScriptFile.js"></script>
</head>
<body>
  <div id="msg">Hello JavaScript!</div>
</body>
</html>
  <!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="msg">Hello JavaScript!</div>

  <script src="myScriptFile.js"></script>
</body>
</html>

Sprint - 유효성 검사

CSS에도 변수가 있습니다. :root 아래에 --변수이름로 시작되는 항목이 변수입니다. 변수를 사용하는 것은 어렵지 않습니다. 속성에 대한 값 대신 var(--변수이름)으로 적용하면 됩니다.
질문: :root는 무슨 의미인가요?
CSS를 구조적으로 짜는 방법을 공부해봅시다.
유효한 상태를 valid라는 상태로 설정한 후, 이에 따라 자식 엘리먼트가 보이게, 혹은 안보이게 만들 수 있습니다. (display: none / display: block)
유효하지 않은 상태를 invalid라는 클래스로 설정한 후, 해당 엘리먼트 아래에는 전체적으로 붉은 색의 스타일링을 할 수 있습니다.

중첩된 CSS를 표현하기 위해 CSS preprocessor를 사용할 수 있습니다.
.input-form과 관련된 자식 스타일을 설정하기 위해 매번 .input-form을 써줘야 하는게 썩 보기에 좋지 않다고 느끼시는 분이 계신가요? 중첩된 CSS 구조를 제대로 표현하지 못하는 CSS의 한계를 뛰어넘기 위해 현업에서는 CSS preprocessor라는 것을 사용하기도 합니다. 추후 프론트엔드를 꿈꾸시는 분들은 한번쯤 공부해봐도 좋은 주제입니다. 이 링크는, CSS preprocessor의 한 종류인 Sass(SCSS) 문법을 사용해서 guide.css 를 구조적으로 만든 예제입니다.

Step 3. UI 구성요소에 이벤트 연결

Step 1에서는 목업을 만들었고, Step 2에서는 유효성 검증 함수를 공부했으니, 이제 기능 하나가 실제로 작동할 수 있게 만들어봅시다. 이렇게 작은 기능 하나를 만들어두고 테스트하기 위해 만드는 작은 앱을 MVP(Minimum Viable Product)라고 합니다. Step 3 에서는 버튼을 클릭했을 때 input box에 입력한 텍스트를 console.log로 출력하고자 하는 기능을 MVP로 구현합니다.

Getting Started
HTML로 UI를 만들었으면, 이것을 자바스크립트의 세계로 소환해야 합니다. 그래야 이벤트도 부여하고, 로직도 만들 수가 있죠.
UI 엘리먼트를 자바스크립트에서 쓸 수 있게 도와주는 핵심 키워드는 바로 앞서 배운 querySelector 입니다.

먼저 어떤 UI 구성요소를 가져와야 할 지 모르겠다면 다음 상황을 생각해보세요. 예를 들어, 버튼을 클릭했을 때 input box에 입력한 텍스트를 console.log로 출력하고자 하는 기능을 만든다고 가정해봅시다.

이를 구현하기 위해 자바스크립트 변수로 만들어야 할 UI 구성요소는 무엇인가요?

버튼
input box

이 HTML 문서가 실제 작동하는 웹 어플리케이션이 되려면 자바스크립트를 활용해야 합니다. 우선 practice/script.js 파일 상단에서 HTML 문서의 정보를 불러오는 querySelector를 사용합니다. ([엘리먼트 변수]라고 적혀있는 주석을 찾아보세요.) 지금은 '회원가입' 버튼의 정보(BtnSignup)만 받아오고 있는데, 여러분들이 Step 1에서 작성한 HTML 문서에서 어떤 정보를 자바스크립트로 가져와야 할지 고민하고 직접 작성해봅시다.

// [엘리먼트 변수]
// 여기에 querySelector를 이용해 상호작용을 해야 하는 모든 엘리먼트를 전역변수로 지정하세요
const btnSignup = document.querySelector('#btn-signup')
const inputbox = document.querySelector('.inputbox')

function handleButtonClick() {
console.log(inputbox.value)
}


button.onclick = handleButtonClick;
profile
임지택입니다.

0개의 댓글