标签:pen baidu hold attr child att rip end parent
<body>
<div id="div1">
<p name="p1">p1内容</p>
<p name="p1">p2内容</p>
<p name="p1">p3内容</p>
</div>
<div id="div2">
<p name="p1">p1内容</p>
<p name="p1">p2内容</p>
<p name="p1">p3内容</p>
</div>
<a href="http://wwww.baidu.com">百度</a>
<ul id="ul">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
<div>
<p id="nodeP">子节点</p>
</div>
<div id="warpInput"></div>
<div id="testInsert">
<p>测试insertBefore(newEle,插入子节点前元素)</p>
</div>
<div id="removeChild">
<p>测试removeChild1</p>
<p>测试removeChild2</p>
</div>
<script type="text/javascript">
//根据name属性获取元素,返回数组
var ep = document.getElementsByName("p1");
ep[0].style.color = "red";
var ep2 = document.getElementsByTagName("p");
ep2[1].style.backgroundColor = "#0000FF";
//只获取 div1 下的所有p
var odiv = document.getElementById("div1");
var childP = odiv.getElementsByTagName("p");
//获取属性 与 设置属性
var ea = document.getElementsByTagName("a")[0];
var strHref = ea.getAttribute("href");
ea.setAttribute("href","http://www.baihe.com");
//获取子节点
var oul = document.getElementById("ul");
// var nodeli = oul.childNodes; 不建议使用,因为会自动将标签后的空格设为一个子节点
var nodeLi = oul.children;
nodeLi[0].style.color = "red";
//通过子元素获取父级节点
var parentP = document.getElementById("nodeP");
parentP.parentNode.style.backgroundColor = "#eee";
//创建元素节点
var oinput = document.createElement("input");
oinput.type = "text";
oinput.placeholder = "请输入内容";
document.getElementById("warpInput").appendChild(oinput);
var testInsert = document.getElementById("testInsert");
var oinput2 = document.createElement("input");
oinput2.type = "text";
oinput2.placeholder = "请输入内容";
//insertBefore(新元素,目标元素);
testInsert.insertBefore(oinput2, testInsert.getElementsByTagName("p")[0]);
//删除节点
var testRemove = document.getElementById("removeChild");
//removeChild(父元素的子节点);
testRemove.removeChild(testRemove.getElementsByTagName("p")[0]);
</script>
</body>
标签:pen baidu hold attr child att rip end parent
原文地址:https://www.cnblogs.com/M87-A/p/12763831.html