节点层级
Node类型
nodeName、nodeType与nodeValue
let element = document.getElementById("test");
let attribute = element.getAttributeNode("id");
let text = element.firstChild;
console.log(element.nodeType);
console.log(attribute.nodeType);
console.log(text.nodeType);
console.log(element.nodeValue);
console.log(attribute.nodeValue);
console.log(text.nodeValue);
console.log(element.nodeName);
console.log(attribute.nodeName);
console.log(text.nodeName);
操作节点
<p id="p3">hello world</p>
<div id="test">
<p id="p1"></p>
<p id="p2"></p>
<p id="p4"></p>
</div>
let test = document.getElementById("test");
let p3 = document.getElementById("p3");
let newNode = test.appendChild(p3);
console.log(test.childNodes);
let test = document.getElementById("test");
let p3 = document.getElementById("p3");
let p1 = document.getElementById("p1");
let newNode = test.insertBefore(p3,p1);
console.log(test.childNodes);
let test = document.getElementById("test");
let p3 = document.getElementById("p3");
let p1 = document.getElementById("p1");
let newNode = test.replaceChild(p3,p1);
console.log(test.childNodes);
Document类型
获取节点
- getElementById、getElementsByClassName和getElementsByTagName
let test1 = document.getElementById("test");
let test2 = document.getElementsByClassName("test");
let test3 = document.getElementsByTagName("p");
文档写入
document.write("<strong>" + (new Date()).toString() + "</strong>");
Element类型
获取属性
let element = document.getElementById("test");
console.log(element.getAttribute("id"));
console.log(element.getAttribute("class"));
let attributes = element.attributes;
console.log(element.attributes.getNamedItem("id").nodeValue);
设置属性
element.setAttribute("style","color:red");
创建元素
let div = document.createElement("div");
document.body.appendChild(div);
Text类型
let div = document.getElementById("test");
let textNode = div.firstChild;
console.log(textNode);
创建文本节点
let element = document.createElement("div");
element.className = "test";
let textNode = document.createTextNode("Hello world!");
element.appendChild(textNode);
document.body.appendChild(element);
DOM扩展
let body = document.querySelector("body");
let myDiv = document.querySelector("#myDiv")
let selected = document.querySelector(".selected")
跟querySelector一样用法返回NodeList
|