DOM 개념정리
오늘은 Javascript로 HTML을 동적으로 만드는데 사용하는 DOM에 대해 공부해 보자.
DOM와 자바스크립트의 관계
DOM은 과연 무엇일까? DOM은 자바스크립트인 것인가?
답은 Nope!
MDN의 정의는 아래와 같다.
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.
간단히 정리하자면 DOM은 자바스크립트로 HTML을 다룰수 있게 하는 API인 셈이다.
쿼리셀렉터 고급활용
기본적으로 DOM에 대해 제일 처음 배우는 것이 바로 .querySelector 메소드이다.
쿼리셀렉터는 사용자의 역량에 따라 복잡한 쿼리문 질의도 가능하다고 한다.
A more complex selector
Selectors can also be really powerful, as demonstrated in the following example. Here, the first <input> element with the name "login" (<input name="login"/>) located inside a <div> whose class is "user-panel main" (<div class="user-panel main">) in the document is returned:
var el = document.querySelector("div.user-panel.main input[name='login']");
위 쿼리문을 해석하자면 "user-panel과 main 클래스를 가진 div엘리먼트 자식중에 name속성이 login인 것을 골라라" 가 된다.
Negation
As all CSS selector strings are valid, you can also negate selectors:
var el = document.querySelector("div.user-panel:not(.main) input[name='login']");
This will select an input with a parent div with the user-panel class but not the main class.
위의 예제처럼 not을 붙이면 자바스크립트의 !와 동일한 기능을 한다.
.remove() VS .innerHTML = ' ';
DOM에는 엘리먼트를 삭제하는 방법이 크게 두가지 있다. 바로 remove와 innerHTML이다.
innerHTML의 경우 원래는 엘리먼트를 삽입하는 값이지만 이 값을 빈칸으로 설정함으로서 삭제가 가능하다.
MDN과 여러 블로그 및 구루들은 해킹의 위험 때문에 가급적 innerHTML의 사용을 피하길 권고하기 때문에 remove를 일단 연습해야 겠다.
HTML Tags VS HTML Elements VS HTML Attributes
DOM을 공부하다보면 태크, 엘리먼트, 어트리뷰트 등 단어가 혼잡하게 사용된다.
이럴 때 일수록 잠시 속도를 늦추고 개념을 잡고가는 것이 중요!
HTML Tags | HTML Elements | HTML Attributes |
HTML tags are used to hold the HTML element. | HTML element holds the content. | HTML attributes are used to describe the characteristic of an HTML element in detail. |
HTML tag starts with < and ends with > | Whatever written within a HTML tag are HTML elements. | HTML attributes are found only in the starting tag. |
HTML tags are almost like keywords where every single tag has unique meaning. | HTML elements specifies the general content. | HTML attributes specify various additional properties to the existing HTML element. |
Element vs Node
그렇다면 Element와 Node는 어떻게 다른 것일까?
우선 노드는 DOM의 모는 것을 지칭한다고 보면 된다.
<!DOCTYPE html> 부터 <!-- > 주석까지 모오오든 것들을 노드라 한다.
반면에 엘리먼트는 태그부분을 뜻한다.
즉 노드가 더 포용적 개념!
만약에 노드리스트를 뽑는다면 HTML에 있는 모든 정보가 딸려나오겠지만,
엘리먼트리스트를 뽑는다면 태그부분만이 간추려저 결과가 나올것이다.
자세한 사항은 아래 블로그에서 상세히 정리가 되어있다.
https://dmitripavlutin.com/dom-node-element/
What's the Difference between DOM Node and Element?
What's the difference between a DOM node and an element? Let's find out!
dmitripavlutin.com
children vs childNodes
children과 childNodes의 개념은 위에서 설명한 element VS node의 개념과 똑같다.
children은 element 자식요소를,
childNodes는 node 요소들을 반환한다.
firstChild vs firstElementChild
이것도 마찬가지!
firstChild는 노드를,
firstElementChild는 엘리먼트 노드만을 반환한다.
removeChild vs remove
removeChild와 remove 메소드는 엘리먼트를 삭제할 수 있는 유용한 메소드 이지만,
영구히 데이터를 삭제하는지 혹은 따로 저장을 해놓는지 여부에 따라 세세한 부분에서 차이가 난다.
removeChild : 데이터는 보존하고 삭제
remove: 영구히 삭제
How to convert nodelist into javascript array
노드리스트는 Array-like object, 즉 유사배열이라고 부른다.
배열의 특징과 성질을 띄지만 사실상 배열이 아니기 때문에 배열이 가진 고유한 메소드를 모두 사용하지 못하는 단점이 있다.
이 부분을 해결하기 위해서는 노드리스트를 배열로 변환해주는 작업이 필요하다.
6가지의 방법을 사용할 수 있는데, 자세한 예문은 아래 사이트에 정리가 잘 되어 있다.
- for
- Array.prototype.slice.call()
- forEach()
- for ...of
- Array.from
- Spread Operator
https://dev.to/emanoellopes/how-to-convert-nodelists-in-arrays-g6j
How to convert NodeLists in arrays
If you have ever had to manipulate and iterate several items in the DOM, you probably already encount...
dev.to