ARCHIVE/JavaScript

[JS] DOM

man_on 2021. 8. 15. 17:49
반응형

 

 

 

     


     

     

     

     

    DOM

     

     

    Document Object Model

    : 웹페이지의 html을 계층화시켜서 트리구조로 만든 객체 모델

    DOM을 활용하면 js로 html태그를 객체처럼 자유롭게 다뤄서 무엇이든 수정가능하고 새로운 콘텐츠 생성가능하다.

     

     

     


     

     

     

    Node

     

     

    각 객체는 node라고 표현한다.

    head (parent node 부모노드) - meta, title (child node)

    head - body (sibling node 형제노드)

     

     

    DOM tree

     

     

    > DOM 이동 시 활용 가능한 프로퍼티

     

     

    Interactive javascript 인터랙티브

    사람들로부터 입력을 받는 것

    인터랙티브 컴퓨터 시스템은 사용자가 데이터나 명령을 입력할 수 있도록 한 프로그램.

    사용자와의 상호작용은 대개 텍스트 기반 또는 그래픽 사용자 인터페이스 둘 모두가 사용

     

     

     

     

    ✔️ 요소 노드 -  태그를 표현하는 노드 (head, body, h1 등)

          텍스트 노드 - 문자열 표현 (dom, 문서객체모델 등)-------요소노드의 자식노드, 자식 가질수 없음

     

    //요소노드 이동
    const myTag = document.querySelector('#idname');
    
    console.log(myTag);
    
    //형제 요소 노드
    console.log(myTag.previousElementSibling);
    console.log(myTag.nextElementSibling);
    
    //부모 요소 노드
    console.log(myTag.parentElement);
    
    //자식 요소 노드
    console.log(myTag.children[1]);
    console.log(myTag.firstElementChild);
    console.log(myTag.lastElementChild)

     

     

     

     

     


     

     

     

     

     

    textContent  /  outerHTML  /  innerHTML / createElement

     

     

    🔻 요소 노드 프로퍼티

     

     textContent : html제외한 텍스트만 가져옴

     outerHTML : 해당요소 포함한 전체 html코드를 문자열로 리턴 ( 줄바꿈, 들여쓰기 포함)

                               새로운 값 할당시 요소자체가 교체되어 버림

     innerHTML : 요소안 html자체를 문자열로 리턴 ( 줄바꿈, 들여쓰기 포함)

                               html수정시 활용( += 기존요소의 마지막으로 태그추가)

    // DOM 트리
    const myTag = document.querySelector('#idname');
    
    // ele.textContext
    console.log(myTag.textContent);
    myTag.textContent = '<li>hi</li>';    //<li>까지 같이 입력되서 교체됨
    
    // ele.outerHTML
    console.log(myTag.outerHTML);
    myTag.outerHTML = '<li>hi</li>';     //처음선택요소 사라지고 대체됨
    
    // ele.innerHTML
    console.log(myTag.innerHTML);
    myTag.innerHTML = '<li>hi</li>'       //기존 요소 사라지고 대체
    myTag.innerHTML += '<li>hi</li>';     //기존 요소의 마지막으로 태그추가
    //ex
    <ul id="doing-list">
        <li>인터랙티브 자바스크립트</li>
        <li>프로그래밍 언어 이해하기</li>
        <li>프로그래머의 세계 이해하기</li>
        <li>소프트웨어 이해하기</li>
    </ul>
      
    
    console.log(doingList.textContext);
    
        인터랙티브 자바스크립트
        프로그래밍 언어 이해하기
        프로그래머의 세계 이해하기
        소프트웨어 이해하기
        
        
    console.log(doingList.outerHTML;
    
    <ul id="doing-list">
        <li>인터랙티브 자바스크립트</li>
        <li>프로그래밍 언어 이해하기</li>
        <li>프로그래머의 세계 이해하기</li>
        <li>소프트웨어 이해하기</li>
    </ul>
    
    
    console.log(doingList.innerHTML);
    
        <li>인터랙티브 자바스크립트</li>
        <li>프로그래밍 언어 이해하기</li>
        <li>프로그래머의 세계 이해하기</li>
        <li>소프트웨어 이해하기</li>

     

     

     

     

    ✔️요소 노드 다루기

     

    createElement

    // 요소 노드 추가하기
    
    const tomorrow = document.querySelector('#tomorrow');
    
    // 1. 요소 노드 만들기: document.createElement('태그이름')
    const first = document.createElement('li');
    
    // 2. 요소 노드 꾸미기: textContent, innerHTML, ...
    first.textContent = '처음';
    
    // 3. 요소 노드 추가 위치: NODE.prepend, append, after, before
    tomorrow.prepend(first);
    tomorrow.appendChild(first);    > 요소뒤에 붙여줌
    
    
    const last = document.createElement('li');
    last.textContent = '마지막';
    tomorrow.append(last);
    
    const prev = document.createElement('p');
    prev.textContent = '이전';
    tomorrow.before(prev);      //메소드를 호출한 노드의 앞
    
    const next = document.createElement('p');
    next.textContent = '다음';
    tomorrow.after(next);

     

     

     

     

    ✔️  노드 삭제/이동

    ( remove / prepend, append, before, after )

     

    const today = document.querySelector('#today');
    const tomorrow = document.querySelector('#tomorrow');
    
    //노드 삭제 : nodeName.remove()
    tomorrow.children[2].remove();
    
    //노드 이동 : ele.prepend, append, before, after
    tomorrow.children[1].after(today.children[1]);
    tomorrow.children[2].before(today.children[1]);
    tomorrow.lastElementChild.before(today.children[1]);

     

     

     

     

     

     

     

     


     

     

     

     

    HTML 속성 다루기

     

     

     

    getAttribute / setAttribute / removeAttribut

     

     : 모든 html속성이 요소노드 프로퍼티로 생성되지않음

       (ex > ol태그에 href추가하면 html표준아님 > 출력하면 undefined출력)

       > html표준아닌 것들은 아래 메소드로 접근

     

    //html속성
    const tomorrow = document.querySelector('#tomorrow');
    const item = tomorrow.firstElementChild;
    const link = item.firstElementChild;
    
    //elem.getAttribute('속성') : 속성에 접근
    console.log(tomorrow.getAttribute('href'));
    console.log(item.getAttribute('class'));
    
    //elem.setAttribute('속성', '값') : 속성 추가(수정)하기
    tomorrow.setAttribute('class', 'list');   //추가
    link.setAttribute('href', 'https://www.naver.com');    //기존에 있으면> 수정!
    
    //elem.removeAttribute('속성') : 속성 제거
    tomorrow.removeAttribute('href');    //대소문자 구별없음

     

     

     

     

     

     

     


     

     

     

     

     

    style 다루기

     

     

    ✔️ Style 다루기 

    style / classList / className

     

       0. querySelector로 요소 선택!

       1. style 프로퍼티 활용하기:   element . style . styleName = 'value';

       권장) class 변경을 통해 간접적으로 스타일 적용하기:  element.className    /   element.classList

     

    const tomorrow = document.querySelector('#tomorrow');
    const today = document.querySelector('#today');
    
    /*
    .done {
       text-decoration: line-through;
     }
     */
     
    // elem.classList : add, remove, toggle   > class 부분 수정
    const item = tomorrow.children[1];
    item.classList.toggle('done')        //toggle은 있으면 삭제 없으면 추가
    
    // elem.className > class속성 통째로 바꾸고 싶을때
     today.children[1].className = 'done';
    
     
    // style 프로퍼티 (camel표기법으로 바꿔서 적어줌)
    today.children[0].style.textDecoration = 'line-through';
    today.children[0].style.backgroundColor = '#DDDDDD';

     

     

     

     

     

     


     

     

     

     

    window

     

     

    ✔️ Global object 전역 객체 = window 객체

    console.log(window);
    console.log(window.innerWidth);     //창의 넓이 출력
    
    window.console.log(~)

     

     

    ✔️ 'resize' 창의 사이즈가 바뀔때

           (body, head, title 등은 querySelector 없이 바로 선택가능)

    window.addEventListener("resize", () => {
      document.body.style.backgroundColor = "tomato";
    });

     

     

     ✔️ 윈도우 객체

     : console, document 등..

       브라우저의 창을 대변 , js의 최상단에 존재 객체 (=윈도우 객체가 js의 다른 모든 객체를 포함)

      ( console.log도 원래 window.console.log로 사용해야하지만 window생략가능 )

     

     

     


     

     

     

    console.log vs console.dir

     

       1. dir은 문자열 표시형식으로 콘솔에 출력

       2. log는 값 자체 (파라미터로 전달받은 값을 위주로)

           dir은 객체의 속성을 자세하게 출력(함수는 속성까지 출력)

       3. log는 메소드 여러값 쉼표로 구분해서 전달하면 모든값을 출력

           dir은 첫번째 값만 출력

       4. DOM객체 다룰때 log는 html형태로 출력

          dir은 대상을 객체형태로 출력

     

     

         console에서 값 자체를 확인하고 싶다면 log를, 객체의 속성을 살펴보고 싶으면 dir을 활용

     

     

     

     

     

    반응형

    'ARCHIVE > JavaScript' 카테고리의 다른 글

    [JS] querySelector  (0) 2021.09.18
    [JS] Event ( addEventListener )  (0) 2021.08.24
    [JS] 함수 ( function )  (0) 2021.08.10
    [JS] array 배열  (0) 2021.08.05
    [JS] Object 객체  (0) 2021.08.05