fan-bk

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>

分类:

技术点:

相关文章:

  • 2021-12-27
  • 2021-10-19
  • 2021-09-17
  • 2022-12-23
  • 2021-04-23
  • 2021-12-25
  • 2022-02-09
  • 2021-12-11
猜你喜欢
  • 2022-02-12
  • 2022-12-23
  • 2022-01-17
  • 2021-12-04
  • 2022-03-15
  • 2021-12-15
  • 2021-12-26
相关资源
相似解决方案