删除HTML节点而不删除其子节点

时间:2015-03-24 16:00:11

标签: javascript html

我遇到了一个我无法解决问题的问题。

我想删除段落而不删除输入。有没有办法做到这一点?

<p id="test">
    <input type="submit" value="testInput">
</p>

目前我正在尝试使用此Javascript代码,但我正在删除任何内容。

var elem = document.getElementById('test');
elem.parentNode.removeChild(elem);

有任何想法是否可能?

&#13;
&#13;
var elem = document.getElementById('test');
	elem.parentNode.removeChild(elem);
&#13;
<p id="test">
	<input type="submit" value="test">
</p>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

最简单的方法是简单地在要删除的元素之前或之后移动元素的内容,然后删除元素本身:

var elem = document.getElementById('test'),
  frag = document.createDocumentFragment();

while (elem.firstChild) {
  frag.appendChild(elem.firstChild);
}

elem.parentNode.insertBefore(frag, elem);
elem.parentNode.removeChild(elem);
<p id="test">
  <input type="submit" value="test">
  <input type="submit" value="test">
  <input type="submit" value="test">
  <input type="submit" value="test">
</p>

或者,作为HTMLElement的方法:

HTMLElement.prototype.unwrapChildren = function() {
  var frag = document.createDocumentFragment(),
    parent = this.parentNode;

  while (this.firstChild) {
    frag.appendChild(this.firstChild);
  }

  parent.insertBefore(frag, this);
  parent.removeChild(this);

};

document.getElementById('test').unwrapChildren();
<p id="test">
  <input type="submit" value="testInput">
</p>

或者,使用Node.replaceChild()

var elem = document.getElementById('test'),
  parent = elem.parentNode,
  frag = document.createDocumentFragment();

while (elem.firstChild) {
  frag.appendChild(elem.firstChild);
}

parent.replaceChild(frag, elem);
<p id="test">
  <input type="submit" value="testInput">
</p>

参考文献:

答案 1 :(得分:2)

移动所有当前内容,然后移除节点:

//Start with your original element
var elem = document.getElementById('test');

//While it contains children, append the first to the parent node
//This will also remove it from the current element
while (elem.childNodes.length > 0) {
    elem.parentNode.appendChild(elem.childNodes[0]);
}

//Finally remove the element
elem.parentNode.removeChild(elem);

答案 2 :(得分:0)

您可以做的是使用querySelectorAll选择所有元素的子元素,然后将它们重新添加到父元素,如下所示。我已经改变了#test的背景颜色,以表明段落实际上已被删除。

// Select all children of your p#test element. Stored in an array.
var input = document.querySelectorAll('#test > *');

// Select your p#test element
var elem = document.getElementById('test');
var parent = elem.parentNode;

// Removes p#test
parent.removeChild(elem);

// Iterates through each item in input and re-adds them into the parent element
for (var i = 0, c = input.length; i < c; i++) {
  parent.appendChild(input[i]);
}
#test {
  background-color: #900;
}
<p id="test">
  <span>Hi!</span>
  <input type="submit" value="Click here" />
</p>