获取节点
1.nodeType
nodeType 属性返回节点的节点类型。
console.log(app.nodeType)
2. getAttributeNode()
3. firtChild
获取第一个子节点
console.log(app.firstChild.nodeType)
4.ChildNodes Children
// childNodes—包含所有的子节点(不管文本还是元素都包含)
// children —只会获取子节点
**
<ul id="app"><li>hello world</li><li>hello world</li><li>hello world</li><li>hello world</li></ul>
// childNodes--包含所有的子节点(不管文本还是元素都包含)// children --只会获取子节点var app = document.getElementById("app");var childs = app.childNodes;var children = app.children;console.log(childs)console.log(children)
// 获取所有的元素节点
var app = document.getElementById("app");var childs = app.childNodes;var arr = [];for(var i=0;i<childs.length;i++){if(childs[i].nodeType == 1){arr.push(childs[i])}}console.log(arr);
增加节点
1. HTML DOM appendChild() 方法
可向节点的子节点列表的末尾添加新的子节点。
document.getElementById("myList").appendChild(newListItem);
2. HTML DOM insertBefore() 方法
可在已有的子节点前插入一个新的子节点
document.getElementById("myList").insertBefore(newItem,existingItem);
3. prepend() 方法和append() 方法
prepend():在被选元素的开头加入内容
append(): 在被选元素的结尾加入内容
<ul id="app"><li>html</li></ul><script>// append,prependvar app = document.getElementById("app");var p = "<h1>hello world<h1>";app.prepend(p);</script>
4. before() 方法和after()方法
before() 方法在被选元素之前插入指定的内容。
after() 方法在被选元素之后插入指定的内容。
<p id="app">hello world</p><script>var app = document.getElementById("app");app.after("world")app.before("hello")</script>
5.createElement()
通过指定名称创建一个元素
var p = document.createElement("p");
6.createTextNode()
可创建文本节点。
var txt = document.createTextNode("hello world");
删除节点
1. removeChild() 方法
方法从被选定元素移除一个或多个类
<div id="app"><div id="child">child</div></div><script>// removeChild()让从元素DOM树,渲染树上都消失var app = document.getElementById("app");var child = document.getElementById("child");app.removeChild(child);</script>
克隆节点
node.cloneNode(true);
<div id="app"><div class="one">hello world</div></div><script>// cloneNodevar app = document.getElementById("app");var one = document.getElementsByClassName("one")[0];var test = one.cloneNode(true);console.log(test);app.appendChild(test);</script>
操作css
3-1 HTML DOM classList 属性
为
元素添加 class:
<style>.current{color: red;}</style><p id="app">hello world</p><button id="btn">移除class</button><script>var app = document.getElementById("app");var btn = document.getElementById("btn");app.onclick = function(){this.classList.add("current")}btn.onclick = function(){\\remove删除指定元素app.classList.remove("current")}</script>
add():
方法将元素插入到指定位置的元素中
addClass():
方法向被选元素添加一个或多个类名**
3-2 toggle() 方法
当点击
元素时进行颜色切换:
<style>.current{color:red;}</style><p id="app">hello world</p><script>var app = document.getElementById("app");app.onclick = function(){// if(this.classList.contains("current")){// this.classList.remove("current")// }else{// this.classList.add("current")// }this.classList.toggle("current")}</script>
toggleClass():
方法对添加和移除被选元素的一个或多个类进行切换。
contains():
方法用于判断字符串中是否包含指定的字符或字符串。
hasClass():
判断是否包含某个class
