慕盖茨71173327
2018-12-01 15:09
有根据内容获取节点的方法么
<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>
你是卿嘉俊?
应该是让练习这个:
<script type="text/javascript"> var otest = document.getElementById("test"); var li = document.createElement('li'); li.innerHTML="PHP"; var html = otest.childNodes[otest.childNodes.length-1]; otest.insertBefore(li, html);</script>
根据内容找到子节点:
<!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>
好像是用:node.innerHTML,
这样 otest.childNodes[i].innerHTML == "HTML"
没有.
JavaScript进阶篇
468061 学习 · 21891 问题
相似问题