日期:2014-05-16  浏览次数:20365 次

如何删除嵌套的html元素
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript"> 
function $(nodeId) 

  return document.getElementById(nodeId); 

function removeMsg() 

  var nodeBtn = $("remove");//按钮 
  document.body.removeChild(nodeBtn); 


</script> 
</head>
<body>
<div id="div1">
<div id="div2">
<input type="button" id="remove" value="删除它" onclick="removeMsg();" /> 
</div>
</div>
</body>
</html>

如果没有div1和div2,按钮可以很顺利地删除,要是有的话,该怎么办???(用jquery实现也行)

------解决方案--------------------
HTML code

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript">  
function $(nodeId)  
{  
  return document.getElementById(nodeId);  
}  
function removeMsg()  
{  
  var nodeBtn = $("remove");//按钮  

  nodeBtn.parentNode.removeChild(nodeBtn);
}  
</script>  
</head>
<body>
<div id="div1">
<div id="div2">
<input type="button" id="remove" value="删除它" onclick="removeMsg();" />  
</div>
</div>
</body>
</html>

------解决方案--------------------
包再多的层 document.getElementById 总找得到控件的吧.
该控件的 parentNode 总有的吧.
有了 parentNode 那 removeChild(按钮控件) 总可以了吧.
------解决方案--------------------
parentNode 或者childNode 来控制就可以了,楼主你分清父子节点就可以了