HTML:
<body>
<select id="books" multiple="multiple" size="5">
<option id="sg">三国演义</option>
<option id="xy">西游记</option>
<option id="sh">水浒传</option>
<option id="hl">红楼梦</option>
</select> <br>
<button onclick="insertLin2RedHouse()">在红楼梦前面插入小林正传</button><br>
<button onclick="insertLinAfterSH()">在水浒传后面插入小林正传</button><br>
<button onclick="removeHLM()">删除红楼梦</button><br>
<button onclick="replaceHL2Lin()">将红楼梦替换成小林正传</button><br>
</body>
JS:
/*
* hasChildNodes()
* appendChild(node)
* removeChild(node)
* replaceChild(newNode,oldNode) 替换子节点
* insertBefore(newNode,refNode) 在一个子节点前插入一个新的子节点
*/
window.onload = function(){
var books = document.getElementById("books");
console.log(books);
};
function insertLin2RedHouse(){
//1.创建小林正传
var option = document.createElement("option");
option.innerHTML = "小林正传";
console.log(option);
//2.找到红楼梦
var hl = document.getElementById("hl");
console.log(hl);
hl.parentNode.insertBefore(option,hl);
//console.log(option);
}
function insertLinAfterSH(){
//1.创建小林正传
var option = document.createElement("option");
option.innerHTML = "小林正传";
//2.找到水浒
var hl = document.getElementById("sh");
var ne = hl.nextSibling;
if(ne != null){
hl.parentNode.insertBefore(option,ne);
}
}
function removeHLM(){
//找到红楼梦
var hl = document.getElementById("hl");
//删除红楼梦
hl.parentNode.removeChild(hl);
}
function replaceHL2Lin(){
//1.创建小林正传
var option = document.createElement("option");
option.innerHTML = "小林正传";
//2.找到红楼梦
var hl = document.getElementById("hl");
var book = document.getElementById("books");
book.replaceChild(option, hl);
}
网友评论