js对html节点的操作
生活随笔
收集整理的這篇文章主要介紹了
js对html节点的操作
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title><style></style><script>function copy(){//克隆節(jié)點//1,得到要克隆的divvar div = document.body.firstElementChild;//2,復(fù)制這個節(jié)點var newDiv = div.cloneNode();document.body.appendChild(newDiv);}function copyAll(){var div = document.body.firstElementChild;//復(fù)制所有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 同理,通過父節(jié)點添加}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 的屬性,屬性節(jié)點根元素節(jié)點的關(guān)系是依附--><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>//表格對象,每個標(biāo)簽可以看作一個對象。可以通過對象建立關(guān)系。//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 而文本節(jié)點 是innerText
1,添加節(jié)點注意
是追加 就 父節(jié)點.appendChild();
是加在一個節(jié)點之前 先找到這個節(jié)點
父節(jié)點.InsertBefore(newNode,oldNode);
具體有添加和移除的 在 下一篇
節(jié)點的添加和移除
2,克隆節(jié)點
var v = div.cloneNode();
var v1 = div.cloneNode(true);// 包含下面的所有子節(jié)點。
把v添加到哪個元素處
3,替換節(jié)點
父元素.replaceNode(new,old);
4,節(jié)點值
nodeValue
元素.nodeValue 為null
文本.nodeValue 為值
5,判斷是否有子節(jié)點
元素.hasChildNodes();
總結(jié)
以上是生活随笔為你收集整理的js对html节点的操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java还是c 2017_2017年9
- 下一篇: java好学还是ui好学_java编程和