js,javascript,删除元素,创建元素,插入子元素

时间:2023-03-08 21:58:50
js,javascript,删除元素,创建元素,插入子元素

删除元素示例代码

<html>
<head>
</head>
<body>
<div>
<div id="delId"><h3>js删除元素之div及其内容</h3><p>这是段落内容</p></div> </div>
<button onclick="fun()">删除div</button>
<script>
function fun(){
//删除div
 var obj = document.getElementById("delId");
  var parentObj = obj.parentNode;//获取div的父对象
  parentObj.removeChild(obj);//通过div的父对象把它删除
}
</script>
</body>
</html>

追加元素代码示例

<html>
<head>
<title> new document </title>
<meta name="generator" content="editplus">
<meta name="author" content="">
<meta name="keywords" content="">
<meta name="description" content="">
</head>
<SCRIPT LANGUAGE="JavaScript">
window.onload = function (){
inp.onclick = function(){
var inp = document.getElementById("list").getElementsByTagName('li')[2]; //在第三个li后面插入一个li
var div = document.createElement("li"); //创建一个li
div.style.cssText = "width:100px;height:100px;border:1px solid red;"; //设置style
//div.id = 'id1'; //赋值id
inp.parentNode.insertBefore(div,inp.nextSibling) //传入参数执行
}
}
</SCRIPT>
<body>
<input type="submit" id="inp" value="添加div" />
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</body>
</html>

插入子元素代码示例

<html>
<head>
<title> new document </title>
<meta name="generator" content="editplus">
<meta name="author" content="">
<meta name="keywords" content="">
<meta name="description" content="">
</head>
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<body>
<script language="javascript">
var o = document.getElementById('list').children[2];
//创建链接
function createA(url,text)
{
var a = document.createElement("a");
a.href = url;
a.innerHTML = text;
a.style.color = "red";
o.appendChild(a);
}
createA("http://www.***.com/","插入子元素");
</script> <script language="javascript">
var o = document.getElementById('list').children[1];
//创建DIV
function createDIV(text)
{
var div = document.createElement("div");
div.innerHTML = text;
o.appendChild(div);
}
createDIV("插入子元素");
</script>
</body>
</html>