8. HTMLDOM 요약

27935 단어
1. HTML DOM(문서 객체 모델)
웹 페이지가 로드되면 브라우저는 웹 페이지의 문서 객체 모델(Document Object Model)을 만듭니다.HTML DOM 모델은 객체의 트리로 구성됩니다.
2. DOM 방법
<!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>

<div id="main">
<p>The DOM is very useful.</p>
<p>  <b>getElementsByTagName</b></p>
</div>

<script>
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
document.write('id   "main"   div  :' + y[0].innerHTML);
</script>

</body>
</html>

 
3. JS의 사건
HTML 이벤트의 예:
사용자가 마우스를 눌렀을 때 onclick웹 페이지가 로드되었을 때이미지가 로드된 경우마우스를 요소로 이동할 때입력 필드가 변경되었을 때HTML 양식을 커밋할 때사용자가 버튼을 터치할 때
 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 <!-- ---------- -->
 5 <h1 onclick="this.innerHTML=' !'"> </h1>
 6 
 7 <!-- ---------- -->
 8 <script>
 9     function changetext(id)
10     {
11         id.innerHTML=" !";
12     }
13 </script>
14 </head>
15 <>
16 
17 <!-- ---------- -->
18 <h1 onclick="changetext(this)"> </h1>
19 
20 <p>  <em>displayDate()</em></p>
21 
22 <button onclick="displayDate()"> </button>
23 
24 <!-- ---------- -->
25 <script>
26     function displayDate()
27     {
28         document.getElementById("demo").innerHTML=Date();
29     }
30 </script>
31 
32 <p id="demo"></p>
33 
34 
35 <p>  <em>displayDate()</em></p>
36 
37 <button id="myBtn"> </button>
38 
39 <!-- ---------- -->
40 <script>
41     document.getElementById("myBtn").onclick=function(){displayDate1()};
42     function displayDate1()
43     {
44         document.getElementById("demo1").innerHTML=Date();
45     }
46 </script>
47 
48 <p id="demo1"></p>
49 
50 
51 <!-------------------------->
52 
53 <div onmouseover="mOver(this)" onmouseout="mOut(this)" onmousedown="mDown(this)" onmouseup="mUp(this)"style="background-color:green;width:120px;height:20px;padding:40px;color:#ffffff;"> </div>
54 
55 <script>
56     function mDown(obj)
57     {
58         obj.style.backgroundColor="#1ec5e5";
59         obj.innerHTML=" "
60     }
61 
62     function mUp(obj)
63     {
64         obj.style.backgroundColor="green";
65         obj.innerHTML=" "
66 
67     }
68 
69     function mOver(obj)
70     {
71         obj.innerHTML=" "
72     }
73 
74     function mOut(obj)
75     {
76         obj.innerHTML=" "
77     }
78 </script>
79 
80 
81 </body>
82 </html>

 
4. JS의 DOM 노드
노드 추가 또는 제거
 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <div id="div1">
 6     <p id="p1"></p>
 7     <p id="p2"></p>
 8 </div>
 9 
10 
11 
12 <!----- ------------->
13 
14 <script>
15 
16     var para=document.createElement("a");
17     var node = document.createTextNode("new anchor");
18 
19     para.setAttribute("href","http://www.baidu.com");
20     para.appendChild(node);
21 
22     var element = document.getElementById("div1");
23     element.appendChild(para);
24 </script>
25 
26 <!----- id p1 ------------->
27 <script>
28 
29     var child = document.getElementById(p1);
30 
31     child.parentNode().remove(child);
32 </script>
33 
34 </body>
35 </html>

좋은 웹페이지 즐겨찾기