JavaScript权威指南笔记7_脚本化文档150423

document.getElementById() 在IE7- 下匹配ID 不区分大小写

document.getElementsByName();document.getElementsByTagName(); 返回 NodeList对象
document.imagesdocument.forms 返回 HTMLCollection 对象
它们都是实时的, 生成静态副本如下:

1
var snapshot = Array.prototype.slice.call(nodelist, 0);

document.getElementsByClassName() IE9+ 支持
document.querySelectorAll() IE8+

文档结构

作为节点树的文档

1
2
3
4
5
6
7
8
9
10
11
12
13
parentNode
childeNodes // 实时
firstChild, lastChild
nextSibling previousChild // 兄弟节点的前/后一个
nodeType // 节点类型
9 Document节点
1 Element节点
3 Text 节点
8 Comment节点
11 DocumentFragment节点

nodeValue Text/Comment 节点的文本内容
nodeName 元素标签名(大写)

作为元素树的节点

1
2
3
4
// IE不可用
firstElementChild lastElementChild
nextElementSibling previousElementChild
childElementCout // 子元素的数量
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// 可移植的文档遍历函数
function parent(e, n) {
if (n === undefined) {
n = 1;
}
while (n-- && e) {
e = e.parentNode;
}
if (!e || e.nodeType !== 1) {
return null;
}
return e;
}

function sibling(e, n) {
while (e && n !== 0) {
if (n > 0) {
if (e.nextElementSibling) {
e = e.nextElementSibling;
}
else {
for (e = e.nextSibling; e && e.nodeType !== 1; e = e.nextSibling) {
/* empty loop */
}
}
n--;
}
else {
if (e.previousElementSibing) {
e = e.previousElementSibling;
}
else {
for (e = e.previousSibling; e && e.nodeType !== 1; e = e.previousSibling) {
/* empty loop */
}
}
n++;
}
}
return e;
}


function child(e, n) {
if (e.children) {
if (n < 0) {
n += e.children.length;
}
if (n < 0) {
return null;
}
return e.children[n];
}


if (n >= 0) {
if (e.firstElementChild) {
e = e.firstElementChild;
}
else {
for (e = e.firstChild; e && e.nodeType !== 1; e = e.nextSibling) {
}
}
return sibling(e, n);
}
else {
if (e.lastElementChild) {
e = e.lastElementChild;
}
else {
for (e = e.lastChild; e && e.nodeType !== 1; e = e.previousSibling) {
}
}
return sibling(e, n + 1);
}
}

属性

HTML属性名不区分大小写; 转换成js时需要小写; 2个以上单词的属性名除第一个单词以外的单词首字母大写
HTML属性名在js中为保留字的,属性名加上前缀’html’; 如 for 属性,js中表示为 htmlfor
class属性在js中 为 className

获取设置非标准HTML属性

属性值都被看成字符串,所以getAttribute()值返回字符串
检测属性hasAttribute; 完全删除属性removeAttribute

数据集属性

H5中,任意以 ‘data-‘ 为前缀的小写的属性都是合法的
dataset-x保存datat-x的值; data-jqueryTest保存data-jquery-test的值

作为Attr节点的属性

Node类型定义了attributes属性
针对非Element对象的任何节点,该属性为null
对于Element对象,attributes属性是只读的,实时的类数组对象

元素内容

作为HTML的元素内容

innerHTML 使用’+=’ 操作效率低下
只有Element节点定义了outerHTML属性

作为纯文本元素的内容

查询纯文本元素内容使用 Node的textContent; IE中使用innerText
innerText不返回