添加
insertbefore方法 是在已有的节点前添加新的节点(相对于子节点来说的)。
-
jQuery :insertBefore() 方法在被选元素之前插入 HTML 标记或已有的元素。
-
语法:$(content).insertBefore(selector)
-
举例:在每个P元素之前插入文字
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("<span>你好!</span>").insertBefore("p");
});
});
</script>
</head><body>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>在每个 p 元素之前插入 span 元素</button>
</body>
</html>
-
-
HTML DOM:insertBefore() 方法在您指定的已有子节点之前插入新的子节点。
- 语法:node.insertBefore(newnode,existingnode)
- 参数
![]()
-
例子:请点击按钮向列表插入一个项目。
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li></ul>
<p id="demo">请点击按钮向列表插入一个项目。</p>
<button onclick="myFunction()">试一下</button>
<script>
function myFunction()
{
var newItem=document.createElement("LI")
var textnode=document.createTextNode("Water")
newItem.appendChild(textnode)var list=document.getElementById("myList")
list.insertBefore(newItem,list.childNodes[0]);
}
</script>
-
nextSibling :某个元素之后紧跟的元素(处于同一树层级中)。 (oTest.insertBefore(newNode,nextSibling);)
reforeNode.nextSibling :取得的是reforeNode对象的紧跟着的下一个节点。 (oTest.insertBefore(newNode,reforeNode);)
previousSibling - 取得某节点的上一个同级节点
append,appendChild方法是在父级节点中的子节点的末尾添加新的节点(相对于父级节点 来说)。
-
jQuery :append() 方法在被选元素的结尾(仍然在内部)插入指定内容。
- 语法:$(selector).append(content)
-
例子,在每个 p 元素的结尾添加内容
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").append(function(n){
return "<b>This p element has index " + n + "</b>";
});
});
});
</script>
</head><body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>在每个 p 元素的结尾添加内容</button>
</body>
</html>
-
HTML DOM appendChild() 方法向节点添加最后一个子节点。
- 语法:node.appendChild(node)
- 例子:请点击按钮向列表中添加项目。
<ul id="myList"><li>Coffee</li><li>Tea</li></ul><p id="demo">请点击按钮向列表中添加项目。</p>
<button onclick="myFunction()">亲自试一试</button>
<script>
function myFunction()
{
var node=document.createElement("LI");
var textnode=document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script> -
从一个列表向另一个列表中移动列表项:
<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul><p id="demo">请点击按钮把项目从一个列表移动到另一个列表中。</p>
<button onclick="myFunction()">亲自试一试</button>
<script>
function myFunction()
{
var node=document.getElementById("myList2").lastChild;
document.getElementById("myList1").appendChild(node);
}
</script>


浙公网安备 33010602011771号