JavaScript學習筆記(四)——DOM

第五章 網頁交互——文本對象模型【Document object model】javascript

1 簡單介紹DOM,dom是將html與javascript進行交互的工具。css

【使用innerHTML時注意:html中的內容是按照HTML自己的前後順序加載的。故js對應代碼應置於html以後】html

問題:java

  *document.getElementById時,id不存在返回null,存在返回對應字符串;node

  *planet.innerHTML其中innerHTML屬性能夠修改字符串的內容;app

  *getElementsByClassName能夠返回類名的元素集合;dom

  *getElementsByTagName返回與指定標籤名匹配的元素;函數

  *innerHTML甚至能夠替換整個body的內容;工具

2 介紹window.onload=函數名;oop

回調函數,在網頁加載完畢後再回調onload指向的指定函數。

3 關於元素的修改

(1)添加新元素

 1 <!DOCTYPE html>
 2 
 3 <html>
 4 
 5 <body>
 6 
 7 <div id="div1">
 8 
 9 <p id="p1">這是一個段落。</p>
10 
11 <p id="p2">這是另外一個段落。</p>
12 
13 </div>
14 
15 <script>
16 
17 var para=document.createElement("p");//建立標籤元素
18 
19 var node=document.createTextNode("這是新段落。");//建立文本
20 
21 para.appendChild(node);//爲p添加文本
22 
23 //爲div1添加元素
24 
25 var element=document.getElementById("div1");
26 
27 element.appendChild(para);
28 
29 </script>
30 
31 </body>
32 
33 </html>

 

(2)修改元素

1 var planet=document.getElementById("p2");//獲取DOM指定ID的元素
2 
3 planet.innerHTML="Red Alert:hit by phaser fire!";//使用innerHtml屬性修改內容

 

(3)刪除元素

 1 <!DOCTYPE html>
 2 
 3 <html>
 4 
 5 <body>
 6 
 7 <div id="div1">
 8 
 9 <p id="p1">這是一個段落。</p>
10 
11 <p id="p2">這是另外一個段落。</p>
12 
13 </div>
14 
15 <script>
16 
17 var parent=document.getElementById("div1");//獲取父元素
18 
19 var child=document.getElementById("p1");//獲取子元素
20 
21 parent.removeChild(child);//刪除
22 
23 </script>
24 
25 </body>
26 
27 </html>

 

4 特性

(1)設置setAttribute();

例如:

 1 planet.setAttribute("class","redtext");//爲planet添加一個class名爲redtext 

(2)獲取特性getAttribute();

例如:

var alttext=scoop.getAttribute("alt");//其中scoop相似於planet,alt爲獲取其值的特性的名稱??

5 完整例子

 1 <!doctype html>
 2 
 3 <html lang="en">
 4 
 5 <head>
 6 
 7 <title>My blog</title>
 8 
 9 <meta charset="utf-8">
10 
11 <style type="text/css">
12 
13 .redtext{
14 
15 color:red;
16 
17 }
18 
19 </style>
20 
21 <script language="JavaScript" type="text/JavaScript">
22 
23 function inni(){
24 
25 var planet=document.getElementById("p2");//獲取DOM指定ID的元素
26 
27 planet.innerHTML="Red Alert:hit by phaser fire!";//使用innerHtml屬性修改內容
28 
29 planet.setAttribute("class","redtext");//設置特性
30 
31 var attribute=planet.getAttribute("text");//獲取特性,返回爲null,不太清楚什麼是特性?
32 
33 console.log("I'm not see the image in the console,but I'm told it looks like:"+attribute);
34 
35 }
36 
37 window.onload=inni;
38 
39 </script>
40 
41 </head>
42 
43 <body>
44 
45 <h1>My blog</h1>
46 
47 <div id="entry1">
48 
49 <h2>Great day bird watching</h2>
50 
51 <p id="p1">
52 
53 Today I saw three ducks!<br />
54 
55 I named them <br />
56 
57 Huey,Louie,and Dewey.
58 
59 </p>
60 
61 <p id="p2">
62 
63 I took a couple of photos...
64 
65 </p>
66 
67 </div>
68 
69 </body>70 </html>
相關文章
相關標籤/搜索