[关闭]
@GivenCui 2016-12-12T18:36:34.000000Z 字数 2310 阅读 716

JS原生DOM总结

DOM



参考

Node 是一个构造函数

doucment instanceof Node

节点的三个属性

  1. nodeType
  2. nodeName
  3. nodeValue

重要的三种节点

  1. 元素节点 (xx.tagName == xx.nodeName)
  2. 属性节点
  3. 文本节点

    * 处为 <div class = "test">123</div>

* nodeType nodeName nodeValue
元素节点 1 "DIV" null
属性节点 2 "class" "test"
文本节点 3 "#test" "123"
  1. <div class = "test">123</div>
  2. 1. 元素节点
  3. nodeType -> 1
  4. nodeName --> "DIV"
  5. nodeValue -> null
  6. 2. 属性节点 (~.getAttributeNode("class") || ~.attributes[idx])
  7. nodeType -> 2
  8. nodeName -> "class"
  9. nodeValue -> "test"
  10. 3. 文本节点 (~.firstChild)
  11. nodeType -> 3
  12. nodeName -> "#text"
  13. nodeValue -> "123"

节点的层次

[ 注意 ] 换行符号算一个空的文本节点

项目 包含文本节点 只包含元素节点
父节点 parentNode parentNode
子节点 childNodes children
第一个节点 firstChild firstElementChild
最后一个节点 lastChild lastElementChild
上一个兄弟节点 previousSibling previousElementSibling
下一个兄弟节点 nextSibling nextElementSibling
所有属性节点 attributes attributes
具体属性节点 getAttribute("") getAttribute("")

操作节点

p = parentNode; xx=待操作节点

  1. hasChildNodes() p.hasChildNodes() // true || false
  2. appendChild() p.appendChild(xx)
  3. insertBefore() p.insertBefore(xx, 某节点)
  4. replaceChild() p.replaceChild(xx, 某节点)
  5. removeChild() p.removeChild(xx)
  6. cloneNode() p.cloneNode(true || false) // 深复制,浅复制
  7. normalize() 未知

查找元素

  1. document.getElementById()
  2. document.getElementsByTagName()
  3. document.getElementsByClassName()
  4. document.getElementsByName()
  5. var html = document.documentElement
  6. var body = document.body

document其他

  1. document.URL
  2. document.domain
  3. document.title
  1. // 实现网站标题滚动效果
  2. var text=document.title
  3. var timerID
  4. function newtext() {
  5. clearTimeout(timerID)
  6. text=text.substring(1,text.length)+text.substring(0,1)
  7. document.title = text;console.log(text);
  8. timerID = setTimeout("newtext()", 100)
  9. };
  10. newtext()

Element类型 (元素节点)

创建元素

document.createElement() // 参数为tagName , e.g. "div"

属性

  1. xx.tagName if(ele.tagName.toLowerCase() == "div"){// 适用HTML和XML}
  2. xx.id
  3. xx.className
  4. xx.title
  5. xx.style 返回对象 xx.style.cssText = "color:red" xx.style.color = "red"
  6. xx.removeAttribute()
  7. xx.setAttribute() 自定义属性不能用此方法设置
  8. xx.getAttribute() 一般取自定义属性时才用
  1. xx.getAttribute()的注意事项 (IE7中和IE8中返回的就不同)
  2. 1. xx.style xx.getAttribute("style")不同,
  3. xx.style返回对象 xx.style.fontSize = "18px";
  4. xx.getAttribute("style") 返回字符串
  5. 2. xx.onclick xx.getAttribute("onclick")不同
  6. xx.onclick返回js函数
  7. xx.getAttribute返回字符串
  8. // 举例添加自定义属性data-index = "1"
  9. // dom的属性节点的操作, 都是字符串
  10. xx.setAttribute("data-index","1"); // 能在html中看见
  11. xx.getAttribute("data-index") // "1"
  12. // dom对象, typeof xx --> object, 本质是给object添加属性
  13. xx["data-index"] = 1
  14. xx["data-index"] // 1
  15. [总结]:
  16. 1. 自定义属性应该用getAttributesetAttribute读写
  17. 2. 实际工作中用jq$.data()方法
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注