有根据内容获取节点的方法么
有根据内容获取节点的方法么
有根据内容获取节点的方法么
2018-12-01
<body>
<ul id="test">
<li>JavaScript</li>
<li>HTML</li>
</ul>
<script type="text/javascript">
// var otest = document.getElementById("test");
// //创建一个新的结点,为节点修改内容,或者其它属性,将该节点通过appendchild()添加给其它节点
// var newnode = document.createElement("li");
// newnode.innerHTML = "PHP";
// otest.appendChild(newnode);
//插入结点insertBefore(newnode, node)向已有的子节点前插入一个新的子节点
var otest_2 = document.getElementById("test");
var nodeList = otest_2.childNodes;
console.log(nodeList);
function insertNode(innerhtml, string) {
var newnode = document.createElement("li");
var newtext = document.createTextNode(string);
newnode.appendChild(newtext);
for (let i = 0; i < nodeList.length; i++) {
if (nodeList[i].innerHTML == innerhtml) {
//
otest_2.insertBefore(newnode, nodeList[i]);
}
}
}
insertNode("HTML","PHP");
// insertNode("PHP","你可以的");
</script>
</body>
根据内容找到子节点:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>
<body>
<ul id="test"><li>JavaScript</li><li>HTML</li></ul>
<script type="text/javascript">
var otest = document.getElementById("test");
var newnode = document.createElement("li");
newnode.innerHTML="php";
var num = otest.childNodes.length;
for(var i=0;i<num;i++){
if(otest.childNodes[i].innerHTML=="HTML"){
otest.insertBefore(newnode,otest.childNodes[i]);
}
}
document.write(otest.childNodes.length);
</script>
</body>
</html>
举报