<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title><style></style><script>function copy(){//克隆节点//1,得到要克隆的divvar div = document.body.firstElementChild;//2,复制这个节点var newDiv = div.cloneNode();document.body.appendChild(newDiv);}function copyAll(){var div = document.body.firstElementChild;//复制所有var newDiv = div.cloneNode(true);document.body.appendChild(newDiv);}function replace(){var div = document.body.firstElementChild;var font = document.createElement("font");font.innerText = "hello girl";document.body.replaceChild(font,div);}function addBefore(){var p = document.getElementById("p");var font = document.createElement("font");font.innerText = "hello girl";document.body.insertBefore(font,p);//还有一个 appendChild 同理,通过父节点添加}function getLi(){var li = document.getElementById("li");alert(li.nodeValue);//null//得到自定义属性的值alert(li.getAttribute("haha"));//哈哈//得到自定义属性的对象alert(li.getAttributeNode("haha"));}function setAttribute1(){var p = document.createElement("p");//要用getAttribute()获取p.setAttribute("haha","哈哈")//p.haha = "哈哈";p.id = "paragraph";p.innerText = "a paragraph";document.body.insertBefore(p,document.body.lastChild);alert(p.id + p.getAttribute("haha"));//哈哈}</script></head><body><div style="border: solid orange; height: 100px;">你好</div> <p id = "p"> JS you are best! </p><button onclick="copy()">clone style</button><button onclick="copyAll()">clone all</button><button onclick = "replace()">replace</button> <button onclick = "addBefore()">insertBefore</button><br /><ul><!--得到 li 的属性,属性节点根元素节点的关系是依附--><li id = "li" value = "666" haha = "哈哈">li1</li><li>li2</li><li>li3</li><li>li4</li></ul><button onclick="getLi()">得到元素里的对象</button><br /><button onclick = "setAttribute1()">属性的取值</button>下面是通过对象进行删除和增加表格的行,列<script>//表格对象,每个标签可以看作一个对象。可以通过对象建立关系。//deleteRow() insertRow() deleteCell 同理function getRow(){var length = tab.rows.length;alert(length)}function addRow(){//插入表格的第一行var tr = tab.insertRow(0);//返回行var arr = [1,'hh',6];for (var i = 0; i < arr.length; i ++){var td = tr.insertCell(i);//返回列td.innerText = arr[i];} }function delRow(){if (tab.rows.length == 4)tab.deleteRow(0);//删除第一行}function attribute(){var a = tab.rows[0].cells[0].height;//自定义的,对于表格alert(tab.height)alert(tab.rows[0].cells[0].getAttribute("height"));//null ,如果没有高度,a则是undefine}</script></body>
</html>
元素nodeValue 是 null 而文本节点 是innerText
1,添加节点注意
是追加 就 父节点.appendChild();
是加在一个节点之前 先找到这个节点
父节点.InsertBefore(newNode,oldNode);
具体有添加和移除的 在 下一篇
节点的添加和移除
2,克隆节点
var v = div.cloneNode();
var v1 = div.cloneNode(true);// 包含下面的所有子节点。
把v添加到哪个元素处
3,替换节点
父元素.replaceNode(new,old);
4,节点值
nodeValue
元素.nodeValue 为null
文本.nodeValue 为值
5,判断是否有子节点
元素.hasChildNodes();