DOM的遍历(查找)
html部分
<div id="wrap">
最大的盒子
<div class="box box1">
这是盒子01
<p id="text">这是段落标签</p>
<span>这是文本标签</span>
</div>
这是box1与box2之间的文本
<div class="box box2">这是盒子02</div>
<div class="box box3">这是盒子03</div>
<ul class="list">
<li>列表项01</li>
<li>列表项02</li>
<li>列表项03</li>
<li>列表项04</li>
</ul>
最大的盒子末尾的文本
</div>
JS部分
获取元素
var oWrap=document.getElementById("wrap");
var oBox1=document.getElementsByClassName("box1")[0];
1. 父子元素间的查找
1.1 children 返回(元素)子节点
console.log(oWrap.children);
1.2 childNodes 返回子节点,包含文本(空)节点 text
console.log(oWrap.childNodes);
1.3 firstElementChild 返回第一子(元素)节点
console.log(oWrap.firstElementChild);
1.4 firstChild 返回第一个子节点(包含文本)
console.log(oWrap.firstChild);
1.5 lastElementChild 返回最后一子(元素)节点
console.log(oWrap.lastElementChild);
1.6 lastChild 返回最后一个子节点(包含文本)
console.log(oWrap.lastChild);
1.7 parentNode 返回父级节点
console.log(oBox1.parentNode);
1.8 parentElement 返回父级(元素)节点
console.log(oBox1.parentElement);
1.9 offsetParent 相对关系 返回第一个由定位属性的祖先元素 如果没有返回body
console.log(oBox1.offsetParent);
链式操作
console.log(oWrap.firstElementChild.firstElementChild);
2 兄弟元素 同胞元素
2.1 nextElementSibling 返回 下一个 兄弟元素节点
console.log(oBox1.nextElementSibling);
2.2 nextSibling 返回下一个兄弟节点 包含文本
console.log(oBox1.nextSibling);
2.3 previousElementSibling 返回 上一个 兄弟元素节点
console.log(oBox1.previousElementSibling);
2.4 previousSibling 返回上一个兄弟节点 包含文本
console.log(oBox1.previousSibling);
var oText=document.getElementById("text");
console.log(oText.parentElement.nextElementSibling.nextElementSibling.nextElementSibling.firstElementChild);
DOM节点的增删改查
html部分
<div class="gaga">
<p class="p1">段落标签1</p>
<p class="p2">段落标签2</p>
<p class="p3">段落标签3</p>
<p class="p4">段落标签4</p>
<p class="p5">段落标签5</p>
</div>
JS部分
1.获取元素
var oGaga=document.getElementsByClassName("gaga")[0];
var aParas=document.getElementsByTagName('p');
2.创建元素
var newP1=document.createElement("P");
newP1.innerText="新建段落标签06";
newP1.style.background="maroon";
var newP2=document.createElement("P");
newP2.innerText="新建段落标签07";
newP2.style.background="lightblue";
var newP3=document.createElement("P");
newP3.innerText="新建段落标签08";
newP3.style.background="purple";
2.1 appendChild() 向父元素子节点末尾添加元素 追加
oGaga.appendChild(newP1);
oGaga.appendChild(newP2);
oGaga.appendChild(newP3);
2.2 insertBefore(添加的节点,参考兄弟元素)
oGaga.insertBefore(newP1,aParas[1]);
2.3兄弟元素 同胞元素
nextElementSibling 返回 下一个 兄弟元素节点
console.log(oGaga.nextElementSibling);
2.4删 移除节点 removedChild(要移除的元素)
oGaga.removeChild(aParas[3]);
2.5改 替换功能 replaceChild(新元素,旧元素)
oGaga.replaceChild(newP2,aParas[2]);