MXOXW

Life always finds a way.

JavaScript 权威指南-脚本化文档

| Comments

15.2 选取文档元素

  • 用指定的id属性;
  • 用指定的name属性;
  • 用指定的标签名字;
  • 用指定的CSS类;
  • 匹配指定的CSS选择器。

15.3 文档结构和遍历

15.3.1 作为节点树的文档

  • parentNode
  • childNodes
  • firstChild, lastChild
  • nextSibling, previousSibling
  • nodeType
    该节点的类型。9代表Document节点,1代表Element节点,3代表Text节点,4代表CDATA节点,8代表Comment节点,11代表documentFragment节点。
  • nodeValue
  • nodeName

15.4 属性

HTML属性名不区分大小写,但JavaScript属性名则大小写敏感。从HTML属性名转换到JavaScript属性名应该采用小写。但是,如果属性名包含不止一个单词,则将除了第一个单词以外的单词的首字母大写,例如:defaultChecked和tabIndex。

有些HTML属性名在JavaScript中是保留字。对于这些属性,一般的规则是为属性名加前缀”html”。例如,HTML的for属性(<lable/>元素)在JavaScript中变为htm1For属性。”class”在JavaScript中是保留字(但还未使用),它是HTML非常重要的class属性,是上面规则的一个例外:在JavaScript代码中它变为className。

  • getAttribute()
  • setAttribute()

dataset

作为attr节点的属性

1
2
3
document.body.attributes[0] // The first attribute of the <body> elt
document.body.attributes.bgcolor // The bgcolor attribute of the <body> elt
document.body.attributes["ONLOAD"] // The onload attribute of the <body> elt

15.5.1 作为HTML的元素的内容
innerHTML的效率非常高,但是用’+=’重复追加一小段文字通常效率底下,因为它既要序列化又要解析。
outerHTML
insertAdjacentHTML()

15.5.2 作为纯文本的元素的内容
textContent
innerText

15.5.3 作为TEXT的元素的内容
nodeValue

1
2
3
4
5
6
7
8
9
10
11
function textContent(e) {
var child, type, s = ""; // s holds the text of all children
for (child = e.firstChild; child != null; child = child.nextSibling) {
type = child.nodeType;
if (type === 3 || type === 4) // Text and CDATASection nodes
s += child.nodeValue;
else if (type === 1) // Recurse for Element nodes
s += textContent(child);
}
return s;
}

15.6.1 创建节点
createElement()
createTextNode()
createDocumentFragment()
createElementNS()
cloneNode()
importNode()

15.6.2 插入节点
appendChild()
insertBefore()

15.6.3 删除和替换节点
removeChild()
replaceChild()

15.6.4 使用 DocumentFragments

1
2
3
4
5
6
7
8
9
10
11
//Reverse the order of the children of Node n
function reverse(n) {
// Create an empty DocumentFragment as a temporary container
var f = document.createDocumentFragment();
// Now loop backward through the children, moving each one to the fragment.
// The last child of n becomes the first child of f, and vice-versa.
// Note that appending a child to f automatically removes it from n.
while (n.lastChild) f.appendChild(n.lastChild);
// Finally, move the children of f all at once back to n, all at once.
n.appendChild(f);
}

15.10.3 查询选取的文本

1
2
3
4
5
6
function getSelectedText() {
if (window.getSelection) // The HTML5 standard API
return window.getSelection().toString();
else if (document.selection) // This is the IE-specific technique.
return document.selection.createRange().text;
}

评论