JavaScript学习笔记(四)——DOM

第五章 网页交互——文本对象模型【Document object model】

1 简单介绍DOM,dom是将html与javascript进行交互的工具。

【使用innerHTML时注意:html中的内容是按照HTML本身的先后顺序加载的。故js对应代码应置于html之后】

问题:

  *document.getElementById时,id不存在返回null,存在返回对应字符串;

  *planet.innerHTML其中innerHTML属性可以修改字符串的内容;

  *getElementsByClassName可以返回类名的元素集合;

  *getElementsByTagName返回与指定标签名匹配的元素;

  *innerHTML甚至可以替换整个body的内容;

2 介绍window.onload=函数名;

回调函数,在网页加载完毕后再回调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>
原文地址:https://www.cnblogs.com/weimingai/p/10349984.html