JavaScript中的appendChild()方法示例詳解
更新時間:2023年10月09日 11:33:42 作者:梁萌
這篇文章主要介紹了JavaScript中的appendChild()方法,appendChild()方法是向節(jié)點(diǎn)添加最后一個子節(jié)點(diǎn),也可以使用此方法從一個元素向另一個元素移動元素,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
1.appendChild() 方法可向節(jié)點(diǎn)的子節(jié)點(diǎn)列表的末尾添加新的子節(jié)點(diǎn)。
實(shí)例一:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
</head>
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li></ul>
<p id="demo">單擊按鈕將項(xiàng)目添加到列表中</p>
<button onclick="myFunction()">點(diǎn)我</button>
<script>
function myFunction(){
var node=document.createElement("LI");
var textnode=document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
<p><strong>注意:</strong><br>首先創(chuàng)建一個節(jié)點(diǎn),<br> 然后創(chuàng)建一個文本節(jié)點(diǎn),<br>然后將文本節(jié)點(diǎn)添加到LI節(jié)點(diǎn)上。<br>最后將節(jié)點(diǎn)添加到列表中。</p>
</body>
</html>頁面效果:

實(shí)例一是向ul中添加li項(xiàng)
2.appendChild() 方法從一個元素向另一個元素移動元素。
實(shí)例二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<select id="select1" multiple="multiple" size="10">
<option>左1</option>
<option>左2</option>
<option>左3</option>
<option>左4</option>
<option>左5</option>
</select>
<span>
<button onclick="toRight()">>></button>
<button onclick="toLeft()"><<</button>
</span>
<select id="select2" multiple="multiple" size="10">
<option>右1</option>
<option>右2</option>
<option>右3</option>
<option>右4</option>
<option>右5</option>
</select>
<script type="text/javascript">
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
function toRight() {
var childs = select1.childNodes;
for (var i = 0; i < childs.length; i++) {
if (childs[i].selected) {
select2.appendChild(childs[i]);
}
}
}
function toLeft() {
var childs = select2.childNodes;
for (var i = 0; i < childs.length; i++) {
if (childs[i].selected) {
select1.appendChild(childs[i]);
}
}
}
</script>
</body>
</html>頁面效果:

實(shí)例二是下拉框選項(xiàng)的移動
總結(jié):
appendChild()方法是向節(jié)點(diǎn)添加最后一個子節(jié)點(diǎn),也可以使用此方法從一個元素向另一個元素移動元素 。
到此這篇關(guān)于JavaScript中的appendChild()方法的文章就介紹到這了,更多相關(guān)jsappendChild()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS實(shí)現(xiàn)div內(nèi)部的文字或圖片自動循環(huán)滾動代碼
在某些情況下需要這樣的功能:使用JS實(shí)現(xiàn)div內(nèi)部的文字或圖片自動循環(huán)滾動,接下來為大家詳細(xì)介紹下實(shí)現(xiàn)方法,感興趣的朋友可以參考下哈2013-04-04
chrome瀏覽器當(dāng)表單自動填充時如何去除瀏覽器自動添加的默認(rèn)樣式
很多朋友都遇到這個問題:當(dāng)使用chrome瀏覽器表單自動填充時都會自動添加默認(rèn)的樣式,該如何去除默認(rèn)樣式呢?看看小編是怎么去除的,需要的朋友一起學(xué)習(xí)吧2015-10-10

