您的位置:首页 > Web前端 > JavaScript

【笔记】 《js权威指南》- 第15章 脚本化文档 - 15.3 - 15.4

2016-04-07 12:57 417 查看
1.文档结构和遍历:

(1).作为节点树的文档:





(2). 作为元素树的文档:

忽略Text和Comment类型的节点:





(3).一些工具函数:

//获取元素的第N个父级节点
function parent(e, n) {
if (n === undefined) n = 1;
while(n-- && e) e = e.parentNode;
if (!e || e.nodeType !== 1) return null;
return e;
}

//获取元素的第n个兄弟元素
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) ;
}
n--;
}
else {
if (e.previousElementSibling) e = e.previousElementSibling;
else {
for (e = e.previousSibling; e && e.nodeType !== 1; e = e.previousSibling) ;
}
n++;
}
}
return e;
}

//获取e的第n代子元素
function child(e, n) {
if (e.children) {
if (n < 0) n += e.children.length;
if (n < 0) return null;
return e.children
;
}

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);
}
}


2. 属性:

(1). 获取和识别非标准的html属性:

getAttribute(), getAttributeNS(), setAttribute(), setAttributeNS(), hasAttribute(), hasAttributeNS(), removeAttribute(), removeAttributeNS();

(2). 数据集属性:

在标签中使用data-前缀命名一个合法属性名,通过元素的dataset属性可以访问他们,

e.g data-jquery-test 对应 dataset.jqueryTest

(3).attributes只读属性:

doucment.body.attributes[0];
document.body.attributes.bgcolor;
document.body.attributes["ONLOAD"];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息