如何删除一个子节点让他的孩子保持javascript?

时间:2016-12-31 00:03:12

标签: javascript

我在javascript方面不太好。 我有这样的DOM结构:

<div data-embed-url="https://www.youtube.com/watch?v=5DkrwfY2jw4">
 <div class="black">
  <div>
   <div style="left: 0px; width: 100%; height: 0px; position: relative; padding-bottom: 56.2493%;">
     <iframe allowfullscreen="" frameborder="0" src="https://www.youtube.com/embed/5DkrwfY2jw4"></iframe>
   </div>
  </div>
 </div>

如何删除类“black”的节点和没有样式和类的div保留其他节点?

3 个答案:

答案 0 :(得分:2)

假设您使用的是ES5:

// Find the `.black`
var black = document.querySelector('.black');

// Replace `.black` with its first child
black.parentNode.replaceChild(black.firstChild, black);

答案 1 :(得分:0)

你应该在你的div上使用ID来操纵DOM。 ID是独一无二的。不鼓励使用类,因为您可以在多个DOM节点上使用类。

// Removing a specified element when knowing its parent node
var d = document.getElementById("top");
var d_nested = document.getElementById("nested");
var throwawayNode = d.removeChild(d_nested);

更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild

使用带有div ID的代码的示例:

// Removing a specified element when knowing its parent node
var d = document.getElementById("blackId");
var d_nested = document.getElementById("blackChildId");
var div_i_want = d_nested.innerHTML;
alert('BEFORE: ' + d.innerHTML);
var throwawayNode = d.removeChild(d_nested);
d.innerHTML = div_i_want;
alert('AFTER: ' + d.innerHTML);
<div data-embed-url="https://www.youtube.com/watch?v=5DkrwfY2jw4">
 <div class="black" id="blackId">
  <div id="blackChildId">
   <div style="left: 0px; width: 100%; height: 0px; position: relative; padding-bottom: 56.2493%;">
     <iframe allowfullscreen="" frameborder="0" src="https://www.youtube.com/embed/5DkrwfY2jw4"></iframe>
   </div>
  </div>
 </div>

答案 2 :(得分:0)

如果您打算删除两个div元素,同时保留嵌套内容(为了简化嵌套),那么您可以像这样使用.replaceChild()

var black = document.querySelector('div.black');
var divToKeep = black.children[0].children[0]; 
black.parentNode.replaceChild(divToKeep, black);