文章目录
DOM-Web API
DOM节点操作
节点属性
var box = document.getElementById("box");
// 元素节点
console.dir(box);
//nodeName: "DIV", nodeType: 1, nodeValue: null
// 属性节点获取
var idnode = box.getAttributeNode("id");
console.dir(idnode);
//nodeName: "id", nodeType: 2, nodeValue: "box"
idnode.nodeValue = "demo";
// 文本节点
var childnodes = box.childNodes;
console.log(childnodes);
//nodeName: "#text", nodeType: 3, nodeValue: "div 1"
childnodes[0].nodeValue = "child 1"; //得到的下标是0
- nodeType节点的类型
- 属性值是数字,表示不同的节点类型共12种,只读
- 1元素节点 2属性节点 3文本节点
- nodeName节点的名称(只读)
- nodeValue节点值
- 返回或设置当前节点的值,元素节点的value始终是null
父子节点
-
childNodes
只读属性,获取一个节点所有子节点的实时集合,动态变化
-
childeren
只读,返回一个节点所有的子元素节点结合,动态更新
-
firstChild
只读,返回该节点的第一个子节点,没有则返回null
-
lastChild
只读,返回该节点的最后一个子节点,没有返回null
-
parentNode
返回一个当前节点的父节点
-
parentElement
返回一个当前节点的父元素节点
var box = document.getElementById("box");
console.log(box.childNodes); //NodeList(5) [text, p, text, span, text]获取所有类型的子节点,其中text中保存的是换行
console.log(box.children); //HTMLCollection(2) [p, span]获取所有元素类型的子节点
console.log(box.firstChild); //#text所有类型的第一个
console.log(box.lastElementChild); //<span>span小盒子</span>所有元素类型的最后一个
console.log(box.parentNode); //<body>……</body>
console.log(box.parentElement); //<body>……</body>
兄弟节点
-
nextSibling
只读,返回与该节点同级的下一个节点,无则返null
-
previousSibling
只读,返回与该节点同级的上一个节点,无则返null
-
nextElementSibling
返回的是下/上一个元素节点(IE9以后才兼容)
-
previousElementSibling
var p3 = my$("p3");
console.log(p3.nextSibling); //#text
console.log(p3.nextElementSibling); // <p>这是段落4</p>
console.log(p3.previousSibling); //#text
console.log(p3.previousElementSibling); // <p>这是段落2</p>
节点操作
-
创建节点
-
document.createElement(“div”)创建元素节点
-
document.createAttribute(“id”)创建属性节点
-
document.createTextNode(“hello”)创建文本节点
-
一般将创建的新节点保存在变量中方便使用,创建的新的节点,是存储在内存中的,并没有添加到DOM树上
//创建一个元素节点 var div = document.createElement("div"); console.dir(div); //nodeValue=1 var id = document.createAttribute("class"); console.dir(id); //nodeValue=2 var txt = document.createTextNode("hello");
-