节点
- 元素节点 : 标签是元素节点
- 属性节点 : 例:Id , name , type , value
- 文本节点 : 例:title、h1、p下的文档
节点属性
- nodeType :节点类型,输出数值。例 1,2,3,,,
- nodeName:(文本#text)
- nodeValue: 属性值,文本内容,可为null。
let h = document.getElementById("h"); console.log("元素节点的nodeType:",h.nodeType);
let attr = h.attributes; console.log("属性节点的nodeType:",attr[1].nodeType); console.log("属性节点的nodeName:",attr[1].nodeName);
let textNode = h.firstChild; console.log("文本节点的nodeType:",textNode.nodeType); console.log("文本节点的nodeName:",textNode.nodeName); console.log("文本节点的nodeValue:",textNode.nodeValue);
节点导航
- firstChild:
- lastChild:
- nextSibling 兄弟级,下一个
console.log(h.nextSibling.nextSibling.nextSibling.nextSibling.previousSibling.previousSibling); // 第一个nextSibling输出结果为空,因两级之间有换行
- previousSibling 兄弟级,上一个
- childNodes 所有子级
- parentNode 父级
let rootElement = document.documentElement;
console.log(rootElement.childNodes);
console.log(h.parentNode);
获取节点方法
- getElementsById Id具有唯一性
- getElementsByTagName 得到所有相同的标签,结果为数组
- getElementsByName 结果为所有相同的name
- 参数可写CSS选择器:
- querySelector 得到相同的第一个
- querySelectorAll 得到所有,数组
节点操作
方法:
创建
- createElement 创建元素节点
- createAttribute 创建属性
- createTextNode 创建文本节点
注:calss 是关键字,不能直接用class,应用calssName
增加
- appendChild 增加到末尾
父级.appendChild(子级)
h3.title = "h3 title"; h3.className = "fontColor"; console.log(h3,text); h3.appendChild(text);
- insertBefore 增加在XX之前
insertBefore(要插入的元素,在XXX之前)
d1.insertBefore(h3,d1.firstChild);
删除
removeChild
let delBtn = document.getElementById("delBtn"); delBtn.onclick = function(){ d1.removeChild(d1.lastChild); }
替换
replaceChild
let replaceBtn = document.getElementById("replaceBtn"); replaceBtn.onclick = function(){ let p = document.createElement("p"); let text = document.createTextNode("段落"); p.appendChild(text); d1.replaceChild(p,d1.firstChild); // p,要替换的内容;d1.firstChild 原本的内容 }