网页编程中获取DOM节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{
position: relative;
}
</style>
</head>
<body>
<ul id="ul1">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div id="div1">
<div id="div2">
<div name="div3" style="width: 100px;height: 100px;
<h1>h1</h1>
</div>
</div>
</div>
<script>
var oulEle = document.getElementById("ul1");
/*获取到所有的子节点,childNodes*/
var oul = document.getElementById("div1");
console.info(oul.childNodes);
for(var i=0;i<oul.childNodes.length;i++){
console.info(oul.childNodes[i].nodeType);
}
/*获取到第一个字节点
* 获取到第一个元素节点:火狐 谷歌-》firstElementChild IE-》firstChild*/
var oul2 = document.getElementById("ul1");
var firstc = oul2.firstChild;
console.info(firstc);
var elementChild = oul2.firstElementChild;
console.info(elementChild);
/*兼容性问题*/
var oul3 = document.getElementById("ul1");
var firstC = oul3.firstElementChild;
//firstC.style.backgroundColor = "red"; //改变当前元素的样式
var elementChilds = oul3.firstElementChild || oul3.firstChild;
elementChilds.style.backgroundColor = "green";
/*获取到最后一个子节点*/
var lastElement = oul2.lastElementChild || oul2.lastChild;
lastElement.style.backgroundColor='red';
/*获取到前一个兄弟节点*/
var odiv = document.getElementById("div1");
var Silbingele = odiv.previousElementSibling || odiv.previousSibling;
console.info(Silbingele.nodeName);
/*获取后一个兄弟节点*/
var nextSil = oulEle.nextElementSibling || oulEle.nextSibling;
console.info(nextSil.nodeName);
/*获取到父节点*/
var odiv2 = document.getElementById("div2");
var parNode = odiv2.parentNode;
console.info(parNode.nodeName);
/*定位父级,偏移父节点*/
var odiv3 = document.getElementById("div3");
var divParent = odiv3.offsetParent;
console.info(divParent.id);
/*获取到属性节点*/
var odiv4 = document.getElementById("div3");
var attrArr = odiv4.attributes;
console.info(attrArr[0].nodeType);
/*直接指定属性的名称*/
console.info(odiv4.id);
/*增加和删除属性*/
odiv4.setAttribute("title","123");
odiv4.removeAttribute("title");
odiv4.title = "123";
/*创建一个节点*/
var op = document.createElement("p");
op.innerHTML = "这是增加的p元素";
var odiv5 = document.getElementById("div3");
//默认增加到最后
odiv5.appendChild(op);
</script>
</body>
</html>