Recent Posts
Recent Comments
Link
06-28 05:11
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

javascript DOM tree 본문

DEV&OPS/Javascript

javascript DOM tree

ALEPH.GEM 2022. 3. 6. 23:24

 

DOM(Document Object Model)

  • document 변수를 통해 접근하는 HTML Element
  • 트리구조로 부모(parent), 자손(child), 형제(siblings)관계로 이루어지고 최상위 조상은 Document 객체입니다.
  • 이벤트 capturing: 이벤트가 발생한 target 요소의 부모로부터 자손까지 이벤트가 일어났는지 검사해 자손의 이벤트를 통보받을 수 있게 등록한 이벤트 핸들러가 있는 지 확인 하는 과정
  • 이벤트 bubling: element들이 부모자손 관계로 중첩될 때 이벤트가 자손부터 실행되어 부모순으로 이벤트 핸들러를 찾아 수행 하며 상위 element로 이벤트를 전파하는 과정

 

주요 프로퍼티

document.documentElement 	//문서 루트 객체 참조
document.head	//문서의 head 요소 참조
document.body	//문서의 body 요소 참조
document.forms[]	//form 요소 참조를 저장한 유사 배열 객체
document.images[]	//img 요소 참조를 저장한 유사 배열 객체
document.anchors[]	//a 요소 참조를 저장한 유사 배열 객체
document.applets[]	//applets 요소 참조를 저장한 유사 배열 객체
document.links[]	//문서의 links 요소 참조를 저장한 유사 배열 객체
document.embeds[]	//문서의 embeds 요소 참조를 저장한 유사 배열 객체
document.plugins[]	//위와 동일한 객체(embeds)를 참조합니다.
document.scripts[]	//문서 안 scripts 요소 참조를 저장한 유사 배열 객체

 

주요 메서드

document.getElementById(id);

document.getElementsByClassName(class); //HTMLElement배열로 return

document.getElementsByTagName(tag); //HTMLElement배열로 return

document.getElementsByName(name어트리뷰트값);		////HTMLElement배열로 return

//CSS 쿼리 셀렉터로도 요소들을 획득할 수 있습니다.
document.querySelector(selector);	//셀렉터와 일치하는 요소들중에서 첫 번째 요소 return
document.querySelectorAll(selector);   //HTMLElement배열로 return

 

attribute (get/set)
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
<a id="gw" href="https://www.daum.net">다음</a>
</body>
<script>
    var anchor = document.getElementById("gw");
    console.log(anchor.href);   
    anchor.setAttribute("href", "https://www.naver.com");
    console.log(anchor.getAttribute("href"));  
</script>
</html>

 

.hasAttribute(속성이름)

요소(elements, tag)에 인수로 전달된 속성(attribute)이름이 있는지 판별합니다. (boolean)

 

.removeAttribute(속성이름)

요소에 인수로 전달된 속성을 삭제합니다.

 

attributes 프로퍼티

요소 객체에서는 그 요소의 모든 속성(attribute)를 모은 attributes 프로퍼티가 NameNodeMap 객체로 존재 합니다.

NameNodeMap의 key는 attribute의 이름이고 value가 attribute의 값이 저장되어 있습니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <p id="controls">
        <input type="button" value="click" onclick="doSomething();">
    </p>
    <script>
        var para = document.getElementById("controls");
        var list = para.firstElementChild.attributes;
        for(var i = 0; i < list.length; i++){
            console.log(list[i].name + ": " + list[i].value);
            /* type: button */
            /* value: click */
            /* onclick: doSomething(); */
        }
    </script>    
</body>
</html>

 

textContent 프로퍼티

요소의 내용을 웹 페이지에 표시될 텍스트 정보를 갖고 있습니다.

태그나 &nbsp; 등 특수문자가 이스케이프되어 웹 페이지에 적용되서 표시되는 문자열로 바뀝니다.

IE9 이전 버전에서는 innerText 프로퍼티를 이용해야 합니다.

하지만 textContent와 innerText 사이에 차이점이 있습니다.

  • textContent는 script 요소 안의 텍스트를 리턴하지만 innerText는 반환하지 않습니다.
  • textContent는 공백문자를 그대로 리턴하지만 innerText는 공백 문자를 제거합니다.
  • innerText는 테이블 요소를 수정할 수 없습니다.

 

노드를 신규 생성하는 주요 메서드

document.createElement(요소이름) : element node object를 생성해 리턴합니다.

document.createAttribute(속성이름) : attribute node object를 생성해 리턴합니다.

document.createTextNode(텍스트) : text node object를 생성해 리턴합니다.

 

노드를 DOM tree에 삽입하는 주요 메서드

요소노드.appendChild(삽입할노드) 

인수로 넘긴 노드를 해당 요소의 마지막 자식 노드로 삽입합니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <ul id="doglist">
        <li>셰퍼드</li>
        <li>달마시안</li>
    </ul>
    <script>
        var doglist = document.getElementById("doglist");
        var element = document.createElement("li");     /* 노드 생성 */
        var text = document.createTextNode("불독");     /* 텍스트 노드 생성 */
        doglist.appendChild(element);       /* ul 엘리먼트의 마지막 자식으로 li 노드를 삽입 */
        element.appendChild(text);      /* li 엘리먼트의 마지막 자식으로 텍스트 노드를 삽입 */
    </script>    
</body>
</html>

 

 

요소노드.insertBefore(삽입할노드, 자식노드)

두번째 인수인 자식노드 바로 앞에 새 노드를 삽입합니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <ul id="doglist">
        <li>셰퍼드</li>
        <li>달마시안</li>
    </ul>
    <script>
        var doglist = document.getElementById("doglist");
        var element = document.createElement("li");     /* 노드 생성 */
        var text = document.createTextNode("불독");     /* 텍스트 노드 생성 */

        /* 두 번째 자식 요소 즉, 달마시안 앞에 불독 삽입 */
        doglist.insertBefore(element, doglist.children[1]);
        element.appendChild(text);
    </script>    
</body>
</html>

노드의 이동

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <ul id="doglist">
        <li>셰퍼드</li>
        <li>달마시안</li>
    </ul>
    <script>
        var doglist = document.getElementById("doglist");
        doglist.appendChild(doglist.children[0]);   /* 첫 번째 자식 요소의 가장 끝에 삽입 */
        /* 이미 있는 노드를 appendChild 하면 기존 노드가 삭제되고 새 위치에 삽입되므로 노드가 이동됩니다. */
    </script>    
</body>
</html>

 

부모노드.removeChild(자식노드)

삭제하려는 노드의 부모 노드에서 removeChild 메서드를 호출해서 노드를 삭제합니다.

 

부모노드.replaceChild(새노드, 자식노드)

인수로 받은 자식노드를 제거하고 새노드로 치환합니다.

 

요소객체.scrollIntoView(alignWithTop);

특정 요소 객체가 있는 곳까지 스크롤 합니다.

alignWithTop은 생략하면 true로 간주하여 top 좌표가 위쪽 끝에 오도록 스크롤 합니다.

<!DOCTYPE html>
<html>
    <meta charset="UTF-8">
    <title> </title>
    <style>
        .box {
            display: inline-block;
            padding: 100px;
            margin: 100px;
            margin-left: 0;
            background-color: yellow;
        }       
    </style>
</head>
<body>
    <div class="box" id="sec1">#sec1</div>
    <br/>
    <div class="box" id="sec2">#sec2</div>
    <br/>
    <div class="box" id="sec3">#sec3</div>
    <br/>
    <div class="box" id="sec4">#sec4</div>
    <br/>
    <div class="box" id="sec5">#sec5</div>
    <br/>
    <div class="box" id="sec6">#sec6</div>
    <br/>
    <script>
        function getScrollTop(){
            if(window.pageYOffset !== undefined){
                return window.pageYOffset;
            }else{
                return document.documentElement.scrollTop || document.body.scrollTop;
            }
        }
        function getScrollLeft(){
            if(window.pageXOffset !== undefined){
                return window.pageXOffset;
            } else {
                return documnet.documentElemnt.scrollLeft || document.body.scrollLeft;
            }
        }
        /* 크롬 스크롤 복원 기능 끔 */
        if('scrollRestoration' in history){
            history.scrollRestoration = 'manual';
        }
        var element = document.getElementById("sec3");
        /* var rect = element.getBoundingClientRect(); */
        /* scrollTo(rect.left + getScrollLeft(), rect.top + getScrollTop()); */
        element.scrollIntoView();   /* 3번재 box가 최상단에 오도록 스크롤 */
    </script>
</body>
</html>

 

FORM element

method attribute

서버로 전송할 때 데이터를 전송하는 방식 즉, POST 혹은 GET 방식을 지정하는 속성입니다.

 

action attribute

서버측에 데이터를 전송할 URL 속성입니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <form method="post" action="./question.do" name="questions" id="form1">
        <label>name: </label>
        <input type="text" name="name">
        <br/>
        <label>gender: </label>
        <input type="radio" name="sex" value="male" onchange="selectGender(this);">남
        <input type="radio" name="sex" value="female" onchange="selectGender(this);">여
        <br/>
        <lable>blood type: </lable>
        <select name="bloodtype" id="menu1">
            <option>A</option>
            <option>B</option>
            <option>O</option>
            <option>AB</option>
        </select>
        <br/>
        <textarea name="opinion" rows="6" cols="80" placeholder="opinion"></textarea>
        <br/>
        <input type="submit" value="submit">
        <input type="reset" value="cancel">
    </form>
    <script>
        var selected;
        var inputs = document.forms.form1.elements.sex;
        for (var i = 0; i < inputs.length; i++){
            if(inputs[i].checked){
                selected = inputs[i].value;
            }
        }
        function selectGender(obj){
            console.log(obj.value);
        }
    </script>
</body>
</html>

 

 

forms 프로퍼티
documnet.forms[0]		//인덱스로 select 합니다. 하지만 동적으로 인덱스가 바뀔 가능성이 있으므로 비추천합니다.
document.forms.form1 		//id로 select
document.forms.questions	//name 으로 select

 

CSS

요소객체.style.프로퍼티이름 = value;

인라인 스타일로 해당 요소 객체의 CSS를 관리합니다.

var element = document.getElementById("title");
element.onclick = function(){
    element.style.backgroundColor = "red";
}

 

 

className
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
    <style>
        .emphasize {
            background-color: pink;
        }
    </style>
</head>
<body>
    <div id="title"> title </div>

    <script>
        var element = document.getElementById("title");
        element.onmouseover = function(){
            element.className = "emphasize";
        };
        element.onmouseout = function(){
            element.className = "";
        }
    </script>
</body>
</html>

 

 

classList
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <p class="note invisible" id="note1">...</p>
    <script>
        var element = document.getElementById("note1");
        var list = element.classList;
        for(var i=0; i<list.length;i++){
            console.log(list[i]);
        }
        /* note */
        /* invisible */
    </script>
</body>
</html>

 

classList.add(클래스이름) : 요소의 클래스를 추가하는 메서드.

classList.remove(클래스이름) :  요소의 클래스를 삭제하는 메서드.

classList.toggle(클래스이름) : 요소의 클래스 목록에 해당 클래스가 없으면 추가하고 있으면 삭제하는 메서드

classList.contains(클래스이름) : 요소의 클래스 목록에 해당 클래스가 있는지 판단(boolean)

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> </title>
</head>
<body>
    <p class="note invisible" id="note1">...</p>
    <script>
        var element = document.getElementById("note1");
        var list = element.classList;
        for(var i=0; i<list.length;i++){
            console.log(list[i]);
        }
        /* note */
        /* invisible */
        list.toggle("invisible");
        console.log(element.className);     /* note */
        list.toggle("invisible");
        console.log(element.className);     /* note invisible */
    </script>
</body>
</html>

 

 

 

 

 

 

728x90

'DEV&OPS > Javascript' 카테고리의 다른 글

javascript 비동기 처리 Promise  (0) 2022.03.12
javascript event  (0) 2022.03.11
javascript 브라우저의 객체  (0) 2022.03.04
javascript 정규 표현식  (0) 2022.03.03
javascript array, map, set  (0) 2022.03.03