2019백업

JavaScript - 노드복제와 템플릿 태그

728x90

HTML 템플렛 태그

<template>
<tr>
    <td><a href=""></a></td>
</tr>
</template>

HTML 컨텐츠 템플릿 (<template>) 엘리먼트는 페이지에 로드될 때 렌더링되지 않지만 JavaScript 를 사용하는 런타임동안에 후속적으로 인스턴트화되는 클라이언트 사이드 컨텐츠를 유지하기 위한 메커니즘입니다.

이는 다큐먼트에서 나중에 사용하기 위해 저장하는 컨텐츠 조각으로 생각하시면 됩니다. 페이지가 로딩되는 동안 파서가 <template> 엘리먼트의 컨텐츠를 처리하지만, 컨텐츠가 유효한지만 확인합니다. 엘리먼트의 컨텐츠는 렌더링되지 않습니다. 

=> template 엘리먼트는 작성한다 틀을 작성하면 실제보이지는 않는다. javascript에서 틀로 사용하기 위해 작성한다.

 

 

JS 속성

querySelector :

css 형식으로 html 태그를 불러오는데 여러개라면 가장 처음 있는 태그를 불러온다. 

 

trNode.cloneNode(true); 

trNode : 복제 될 값 
(true): 복제하는 속성으로 해당 node의 children 까지 복제하려면 true, 해당 node 만 복제하려면 false를 입력한다.
참고: https://developer.mozilla.org/ko/docs/Web/API/Node/cloneNode

var tds = cloneNode.querySelectorAll("td");

Document 메소드 querySelectorAll() 는 지정된 셀렉터 그룹에 일치하는 다큐먼트의 엘리먼트 리스트를 나타내는 정적(살아 있지 않은) NodeList 를 반환합니다.
-> querySelector는 처음 접근하는 지정한  HTML 태그를 가져오지만 querySelectorAll은 전부 가져온다.
참고: https://developer.mozilla.org/ko/docs/Web/API/Document/querySelectorAll

tds[0].textContent 

Node.textContent 프로퍼티는 노드와 그 자손의 텍스트 내용을 표시한다.

  • 만약 요소가 문서, 문서 형식 혹은 표기법일 때 textContent 는 null 값을 반환한다. 문서 전체의 텍스트와 CDATA 데이터를 선택하는 한가지 방법은 document.documentElement.textContent를 사용하는 것이다.
  • 만약 노드가 CDATA 섹션, 주석, 처리 명령 혹은 텍스트 노드일 때, textContent는 해당 노드(nodeValue) 안의 텍스트를 반환한다.
  • 다른 유형의 노드에서 textContent 는 연쇄적으로 모든 자식 노드의 주석과 처리 명령을 제외한 textContent 프로퍼티를 반환한다. 만약 자식 노드가 없다면 빈 문자열을 반환한다.
  • 이 프로퍼티를 설정하면 해당 노드의 자식 노드 모두를 지우고 그것들을 주어진 값인 단일 텍스트 노드로 대체한다.

    innerText와의 차이점

    • textContent가 <script>와 <style> 요소를 포함한 모든 요소들의 내용을 가져오는 반면 innerText는 그렇지 않다.
    • innerText는 style을 인지하고 숨겨진 요소들의 텍스트를 반환하지 않지만 textContent는 반환한다.
    • innerText는 CSS 스타일링을 인지하기 때문에 레이아웃의 변화를 가져올 수 있지만 textContent는 그렇지 않다.
    • textContent와는 달리 (버전 11 까지를 포함한) Internet Explorer에서 innerText를 대신 사용하면 요소의 자식 노드를 지우는 것 뿐만이 아니라 텍스트 노드의 모든 자손을 영구적으로 제거한다. (그래서 더이상 해당 노드를 다른 요소 혹은 같은 요소에 다시 삽입하는게 불가능해진다.)

    innerHTML과의 차이점

  • Element.innerHTML는 그것의 이름이 나타내는 HTML을 반환한다. 꽤 자주, 검색 혹은 요소 안에 텍스트 작성을 위해 사람들이 innerHTML을 사용하지만, textContent가 텍스트를 HTML로 파싱하지 않기 때문에 종종 더 좋은 성능을 보여준다. 게다가 textContent를 사용하면 XSS(크로스 사이트 스크립팅) 공격을 방지할 수 있다.

 

tbodyNode.appendChild(cloneNode);

  • Node.appendChild() 메소드는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙입니다.
    Node.appendChild()는 하나의 인자를 받지만 Node.append()는 text, 여러 인자를 넣을 수 있다.
    예전 버젼의 브라우저의 호환성을 위해 사용하는 경우가 아니라면 append()를 사용한다.

 

 //importNode -> cloneNode와 비슷한 역할 

 let cloneNode = document.importNode(template.content, true);

  • 현재 문서가 아닌 외부 문서의 노드를 복사하여 현재 문서에 넣을 수 있도록 해줍니다.

문법

  • var node = document.importNode(externalNode, deep);
  • node문서에 추가될 새로운 노드입니다. 새로운 노드가 문서 트리에 추가되기 전까지, 새로운 노드의 parentNode는 null입니다.
  • externalNode다른 문서에서 가져올 노드입니다.
  • deep불리언 타입을 가지며, 다른 문서에서 노드를 가져올 때 노드의 자식 요소들을 포함하여 가져올 것인지에 대한 여부를 결정합니다.

예제 )

 

HTML코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<section id="section7">
        <h1>Ex7 노드복제와 템플릿 태그</h1>
        <div>
            <input type="button" class="clone-button" value="복제하기">
            <input type="button" class="template-button" value="템플릿 복제하기">
        </div>
        <template>
            <tr>
                <td></td>
                <td><a href=""></a></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </template>
        <table border="1" class="notice-list">
            <thead>
                <tr>
                    <td>번호</td>
                    <td>제목</td>
                    <td>작성일</td>
                    <td>작성자</td>
                    <td>조회수</td>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td>1</td>
                    <td><a href="1">자바스크립트란..</a></td>
                    <td>2019-01-25</td>
                    <td>newlect</td>
                    <td>7</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td><a href="1">기초부터 </a></td>
                    <td>2019-01-25</td>
                    <td>newlect</td>
                    <td>9</td>
                </tr> -->
            </tbody>
        </table>
    </section>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

JS코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//Ex7 : 노드복제와 템플릿 태그
window.addEventListener("load"function() {
    let notices = [
        {id:5, title:"퐈이야~~",regDate:"2019-07-24",writerId:"hoon", hit:2 },
        {id:6, title:"복제하기~~",regDate:"2019-07-24",writerId:"hoon", hit:17 }
    ];
    var section = document.querySelector("#section7");
 
    var noticeList = section.querySelector(".notice-list");
    var cloneButton = section.querySelector(".clone-button");
    var templateButton = section.querySelector(".template-button");
    var tbodyNode = noticeList.querySelector("tbody");
 
    cloneButton.onclick = function() {
        var trNode = noticeList.querySelector("tbody tr");
        var cloneNode = trNode.cloneNode(true);
        var tds = cloneNode.querySelectorAll("td");
       
        for (let i = 0; i < notices.length; i++) {
            tds[0].textContent = notices[i].id;
            // tds[1].innerHTML = '<a href="+notices[0].id+">'+ notices[0].title+'</a>';
            // 주석처리한 것과 동일 한것 
            var aNode = tds[1].children[i];
            aNode.href = notices[i].id;
            aNode.textContent = notices[i].title;
            tds[2].textContent = notices[i].regDate;
            tds[3].textContent = notices[i].writerId;
            tds[4].textContent = notices[i].hit;
 
            tbodyNode.appendChild(cloneNode);
        }
    };
 
    templateButton.onclick = function() {
        
        for (let i = 0; i < 2; i++) {
            let template = section.querySelector("template");
            //importNode -> cloneNode와 비슷한 역할 
            let cloneNode = document.importNode(template.contenttrue);
            let tds = cloneNode.querySelectorAll("td");
            tds[0].textContent = notices[i].id;
            tds[1].innerHTML = '<a href="+notices[0].id+">'+ notices[i].title+'</a>';
            tds[2].textContent = notices[i].regDate;
            tds[3].textContent = notices[i].writerId;
            tds[4].textContent = notices[i].hit;
 
            tbodyNode.appendChild(cloneNode);
        }
    };
 
});
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
반응형