본문 바로가기

   
Programming/Javascript

Form, DOM

반응형



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>Form</title>

 

       <style type="text/css">

             #list1

             {

                    width:600px;

                    border:1px solid gray;

                    border-collapse:collapse;

             }

             #list1 td

             {

                    border:1px solid gray;

                    font-size:12px;

                    padding:2px;

             }

             #list1 #header

             {

                    font-weight:bold;

                    text-align:center;

                    background-color:Yellow;

             }

       </style>

 

 

       <script type="text/javascript">

 

             function Test(f)

             {

                    //var txt1 = document.forms[0]

                    //var txt1 = document.forms["form1"]

                    //var txt1 = f.txt1;

                    var txt0 = document.form1.txt0;

                    txt0.value = "텍스트값";

 

                    var cb1 = f.cb1;

                    cb1.checked = true;

             }

 

 

             function Test2()

             {

                    //BOM에서 form의 자식을 배열로 제공..

                    var list = document.form2.elements;

                    //alert(list.length);

 

                    for (i = 0; i < list.length; i++)

                    {

                           //list[i].value = "테스트" + i;

                           //alert(list[i].type); //type 지정한것 확인

                           //alert(list[i].className); //class네임 지정하여 준것

                           if (list[i].type == "text" && list[i].className == "t1")

                           {

                                 list[i].value = "하하하";

                           }

 

                          

                    }

             }

 

             function Test3()

             {

                    alert(document.form3.txt.length);

             }

 

             function Check(cb)

             {

                    //alert(cb.checked)

 

                    //모든 메일앞에 있는 체크박스들..

                    var cbList = document.form4.cbMail;

 

                    //if (cb.checked)

                    //{

                    //for -> true

                    //}

                    //else

                    //{

                    //for -> false

                    //}

 

                    var b = cb.checked;

 

                    for (i = 0; i < cbList.length; i++)

                    {

                           cbList[i].checked = b;

                    }

             }

 

       </script>

</head>

<body>

       <!--Ex17_form.htm-->

       <form name="form1">

             <input type="text" name="txt0" /><br />

             <input type="checkbox" name="cb1" /><br />

             <input type="button" value=" 테스트 " onclick="Test(this.form);" />

       </form>

 

       <hr />

 

       <form name="form2">

             <!--Bom 태그엔 br 태그는 BOM태그에 없기 때문에 자식으로 취급하지 않는다.-->

             <input type="text" name="txt1" /><br />

             <input type="text" name="txt2" class="t1" /><br />

             <input type="text" name="txt3" class="t1" /><br />

             <input type="text" name="txt4" /><br />

             <input type="text" name="txt5" class="t1" /><br />

             <input type="button" value="테스트" onclick="Test2();" />

       </form>

 

       <hr />

 

       <form name="form3">

             <input type="text" name="txt" /><br />

             <input type="text" name="txt" /><br />

             <input type="button" value="테스트" onclick="Test3();" /><br />

       </form>

       <br /> <br />

 

       <h3>받은 편지함</h3>

      

       <form name="form4">

             <table id="list1">

                    <tr id="header">

                           <td><input type="checkbox" onclick="Check(this);" /></td>

                           <td>제목</td>

                           <td>보낸사람</td>

                           <td>받는사람</td>

                           <td>날짜</td>

                    </tr>

 

                    <tr>

                           <td><input type="checkbox" name="cbMail" /></td>

                           <td>이메일 테스트 입니다.</td>

                           <td>test@test.com</td>

                           <td>administrator@naver.com</td>

                           <td>2012.05.20 15:20:30</td>

                    </tr>

 

                    <tr>

                           <td><input type="checkbox" name="cbMail" /></td>

                           <td>이메일 테스트 입니다.</td>

                           <td>test@test.com</td>

                           <td>administrator@naver.com</td>

                           <td>2012.05.20 15:20:30</td>

                    </tr>

 

                    <tr>

                           <td><input type="checkbox" name="cbMail" /></td>

                           <td>이메일 테스트 입니다.</td>

                           <td>test@test.com</td>

                           <td>administrator@naver.com</td>

                           <td>2012.05.20 15:20:30</td>

                    </tr>

 

                    <tr>

                           <td><input type="checkbox" name="cbMail" /></td>

                           <td>이메일 테스트 입니다.</td>

                           <td>test@test.com</td>

                           <td>administrator@naver.com</td>

                           <td>2012.05.20 15:20:30</td>

                    </tr>

             </table>

       </form>

       <hr />

 

</body>

</html>

 




DOM 



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>DOM</title>

 

       <style type="text/css">

             #list1 li

             {

                    font-size:12px;

                    margin-bottom:5px;

             }

       </style>

 

       <script type="text/javascript">

             //name -> BOM

             //ID -> DOM

             function Test()

             {

                    //1. BOM

                    //var txt1 = document.form1.txt1;

 

                    //2. DOM

                    //document : DOM BOM객체의 일부를 차용함

                    //계층 구조가 어디에 있든지 상관없이 ID는 문서내에서 유일하니까..

                    var txt1 = document.getElementById("txt1");

 

                    var img = document.getElementById("a1");

 

                    var div = document.getElementById("div1");

 

 

 

                    div.innerText = "히히히";

 

                    //alert(div.innerHTML);

                    //alert(txt1.value);

                    //alert(img);

 

                    //배열 반환 몇번째 객체인지 체크해야한다.

                    //document.getElementsByName("txt1")[0].value = "호호호";

 

                    //문서상에 있는 input 붙은애는 다가져와라.

                    var list = document.getElementsByTagName("input");

 

                    //for (var i = 0; i < list.length; i++)

                    //{

                    //     alert(list[i].value="aaaaa");

                    //}

 

                    //DOM - 접근

                    // 트리구조 -> 아이템 -> 노드(Node), TreeView

                    //alert(document.body.childNodes.length);

                    //alert(document.body.childNodes[0].tagName);

 

                    //document.getElementById("box").childNodes[1].innerText = "21";

 

                    //처음 코딩한것

                    document.getElementById("box").firstChild;

                    //그다음으로 코딩한것

                    document.getElementById("box").lastChild;

                    //형동생들 그리고 코딩순서(객체가 만들어지는 순서

                    //동등한 형제겪중에 다음 코딩한것

                    document.getElementById("box").nextSibling;

                    //그다음 객체

                    document.getElementById("box").previousSibling;

                    //친부모

                    document.getElementById("box").parentNode;

 

                    //최상위 객체에서 여러갈래로 파생

 

                    //** 모든 태그에 식별자를 붙일수 없다. 누군가를 기준으로 삼고 상대적으로 찾을수 있는 방법 을가지고 있는것이 DOM이다.

 

                    //문서상에 존재하는 모든 태그를 찾을수 있다.

             }

 

 

             function Test2()

             {

                    var item = document.getElementById("list1").childNodes[3]; //<li>아무게</li>

                    //alert(item.innerText);

                    item.innerText = "아무게";

 

                    //동적으로 타입 변경 속성값 반환

                    //alert(item.getAttribute("type"));

                    item.setAttribute("type", "circle");//속성값 쓰기

             }

 

             function Init()

             {

                    var items = document.getElementById("list2").childNodes;

 

                    for (var i = 0; i < items.length; i++)

                    {

                           //alert(items[i].tagName);

                           //alert(items[i].nodeType);//1-태그, 3-텍스트

 

                           if (items[i].nodeType == 1 && items[i].tagName == "LI")

                           {

                                 //<li>태그

                                 //alert(items[i].innerText);

 

                                 //클릭할떄마다 익명함수 호출

                                 items[i].onclick = function ()

                                 {

                                        if (event.srcElement.type != "circle")

                                              event.srcElement.type = "circle";

                                        else

                                              event.srcElement.type = "disc";

                                 };

                           }

                    }

             }

            

       </script>

 

</head>

<body onload="Init();">

       <form name="form1">

             <a href="Ex010_link.htm" id="a1">링크</a>

             <div id="div1">영역입니다.</div>

             <input type="text" name="txt1" id="txt1" /><br />

 

             <div id="box">

                    <div>하하하</div>

                    <div>20</div>

                    <div>서울시</div>

             </div>

            

             <input type="button" value="테스트" onclick="Test();" />

       </form>

 

       <hr />

      

       <h3>회원 명단</h3>

       <ul id="list1">

             <li>홍길동</li>

             <li>아무게</li>

             <li>하하하</li>

             <li type="disk">테스트</li>

       </ul>

 

       <input type="button" value="테스트" onclick="Test2();" />

 

       <hr />

 

       <h3>회원 명단</h3>

       <ul id="list2">

             <li>홍길동</li>

             <li>아무게</li>

             <li>하하하</li>

             <li type="disk">테스트</li>

       </ul>

 

       <input type="button" value="테스트" onclick="Test2();" />

 

 

</body>

</html>

 





<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>DOM</title>

 

       <style type="text/css">

             body, div, p, span, th, td, li, a, input, textarea

             {

                    font-family:굴림;

                    font-size:12px;

             }

            

             #list

             {

                    width:400px;

                    border:1px solid gray;

                    border-collapse:collapse;

                    text-align:center;

             }

            

             #list td, #list th

             {

                    border:1px solid gray;

                    text-align:center;

                    padding:3px;

             }

            

       </style>

 

       <script type="text/javascript">

             function Test()

             {

                    //요소얻기

                    var div1 = document.getElementById("div1");

 

                    //1. 요소의 텍스트를 접근(get/set)

                    div1.innerText = "홍길동";

 

                    //2. 요소의 속성 접근(get/set)

                    div1.title = "영역입니다.";

 

                    //3. 요소를 동적으로 추가

                    //<h3>제목</h3>

                    // - 모든 요소의 생성은 document가 담당

                   

                    //태그 생성후 누군가의 자식으로 넣어줘야한다.

                    var h3 = document.createElement("h3");

                    h3.innerText = "제목입니다";

                    h3.setAttribute("title", "풍선도움말"); //DOM

                    div1.appendChild(h3); //자식중 막내로 추가

                    //div1.insertBefore

 

             }

 

             var n = 0;

 

             function Test2()

             {

 

                    //<img />

                    var img = document.createElement("img");

 

                    //<img src="num/0.png" />

                    img.setAttribute("src", "num/" + n + ".png");

 

                    //<img onclick="" />

                    img.onclick = function ()

                    {

                           //document.body.removeChild(event.srcElement);

                           event.srcElement.parentNode.removeChild(event.srcElement);

                    };

 

                    //누구 자식인지 지정~ 막내로

                    //document.body.appendChild(img);

 

                    //끼워 넣는다. (맨마지막이 아닌(막내) 지정된 곳 위에 끼워 넣는다.

                    document.body.insertBefore(img, document.getElementById("div1"));

 

                    n++;

 

                    if (n == 10) n = 0;

             }

 

             function Test3()

             {

                    //요소 삭제

                    //document.body.removeChild(document.getElementById("btn1"));

 

                    //차례대로 지워진다. 굿!

                    document.body.removeChild(document.body.firstChild);

 

                    var list = document.body.childNodes;

 

                    for (var i = list.length - 1; i >= 0; i--)

                    {

                           //끝에서부터 지워야 인덱스 에러가 안나지~~

                           document.body.removeChild(list[i]);

                    }

 

                    //<img src="num/0.png" />

 

             }

 

             var num = 1;

 

             //메모 추가

             function AddMemo()

             {

                    //1. 번호 -> num

                    //2. 메모

                    var memo = document.getElementById("txtMemo").value;

 

                    //3. 그룹

                    var group = document.getElementById("selGroup").value;

 

                    //동적으로 <tr>, <td>생성 -> 추가

                    //A. <tr>

                    var tr = document.createElement("tr");

 

                    //B. <td> x 3

                    var td1 = document.createElement("td");

                    var td2 = document.createElement("td");

                    var td3 = document.createElement("td");

 

                    //C. <tr> + <td>

                    tr.appendChild(td1);

                    tr.appendChild(td2);

                    tr.appendChild(td3);

 

                    //D 내용물 채우기.

                    td1.innerText = num; //메모번호

                    num++;

 

                    td2.innerText = memo; //메모 내용

 

                    var img = document.createElement("img");

                    img.setAttribute("src", "images/" + group + ".png");

                    img.setAttribute("width", "20px");

 

                    td3.appendChild(img);

 

                    //E. <tr>을 테이블 추가

                    //alert(document.getElementById("list").firstChild.tagName);

                    document.getElementById("list").childNodes[1].appendChild(tr);

             }

 

       </script>

 

</head>

<body>

 

       <div id="div1"></div>

       <input type="button" value="테스트1" id="btn1" onclick="Test();" />

 

       <input type="button" value="테스트2" onclick="Test2();" />

 

       <input type="button" value="테스트3" onclick="Test3();" />

      

       <hr />

 

             <h3>메모 리스트</h3>

             <!--

             테이블 태그는 보이지 않지만 <tbody></tbody> 태그등이 있다.

             브라우저는 테이블태그를 읽어 들일떄 원형 전체로 알고 있다.

             -->

       <table id="list">

             <tr>

                    <th>번호</th>

                    <th>메모</th>

                    <th>그룹</th>

             </tr>

       </table>

 

       <hr />

 

       메모 : <input type="text" id="txtMemo" /><br />

       그룹 : <select id="selGroup">

                    <option value="1">개인</option>

                    <option value="2">회사</option>

                    <option value="3">학교</option>

       </select>

       <br />

       <input type="button" value=" 추가하기 " onclick="AddMemo();" />

</body>

</html>

 

 


document의 주요 기능

document.getElementById("id")

- param : 검색할 id

- return : 검색된 엘리먼트 하나


document.getElementsByTagName("tagname")

- param : 검색할 태그명

- return : 검색된 엘리먼트가 포함된 배열


document.getElementsByClassName("classname")

- param : 검색할 클래스명

- return : 검색된 엘리먼트가 포함된 배열


document.createElement("tagname")

- param : 생성할 태그명

- return : 새로 만들어진 엘리먼트


document.createTextNode("textcontent")

- param : 문자열

- return : 문자열을 포함하고 있는 textnode


element의 주요 속성과 기능

속성

element.firstChild

- 해당 엘리먼트의 첫번째 자식 엘리먼트

element.lastChild

- 해당 엘리먼트의 마지막 자식 엘리먼트

element.childNodes

- 해당 엘리먼트의 모든 자식 엘리먼트가 포함된 배열

element.parentNode

- 해당 엘리먼트의 부모 엘리먼트

element.previousSibling

- 해당 엘리먼트의 형 엘리먼트

element.nextSibling

- 해당 엘리먼트의 동생 엘리먼트


element.tagName

- 해당 엘리먼트의 태그명

element.id

- 해당 엘리먼트이 id

element.className

- 해당 엘리먼트의 클래스명

element.textContent

- 해당 엘리먼트에 포함된 텍스트컨텐츠

element.innerHTML

- 해당 엘리먼트에 포함된 html내용


기능

element.getElementsByTagName('tagname')

element.getElementsByClassName('classname')

element.hasChildNodes()

- return : 해당 엘리먼트가 자식노드를 가지고 있으면 true


element.appendChild(node)

- param : 해당 엘리먼트의 자식으로 추가할 자식노드


element.insertBefore(newNode, existNode)

- param : 새로 추가할 자식노드

 기존노드

element.removeChild(node)

- param : 삭제할 자식노드


element.getAttribute('attributeName')

- param : 값을 조회할 속성명

- return : 속성값(문자열)


element.setAttribute('attributeName', 'attributeValue')

- param : 추가할 속성명, 추가할 속성값


element.removeAttribute('attributeName')

- param : 삭제할 속성명


element.hasAttribute('attributeName')

- param : 조회할 속성명

- return : 속성이 존재하면 true


 

 

반응형