Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only the parent element and not its child elements in JavaScript?

Tags:

javascript

dom

Let's say:

<div>   pre text   <div class="remove-just-this">     <p>child foo</p>     <p>child bar</p>     nested text   </div>   post text </div> 

to this:

<div>   pre text   <p>child foo</p>   <p>child bar</p>   nested text   post text </div> 

I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.

like image 279
cheeaun Avatar asked Oct 04 '08 08:10

cheeaun


People also ask

How do you remove the parent element without removing a child?

To remove the parent element without removing its children, call the replaceWith() method on the parent element passing it the child nodes as a parameter, e.g. parent. replaceWith(... parent. childNodes) .

How do you check if an element is a child of a parent in JavaScript?

To check if an element is a child of a parent with JavaScript, we can use the parent element's contains method. const contains = (parent, child) => { return parent !== child && parent. contains(child); };

How do you remove an element in JavaScript?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.


2 Answers

Using jQuery you can do this:

var cnt = $(".remove-just-this").contents(); $(".remove-just-this").replaceWith(cnt); 

Quick links to the documentation:

  • contents( ) : jQuery
  • replaceWith( content : [String | Element | jQuery] ) : jQuery
like image 135
jk. Avatar answered Sep 18 '22 04:09

jk.


The library-independent method is to insert all child nodes of the element to be removed before itself (which implicitly removes them from their old position), before you remove it:

while (nodeToBeRemoved.firstChild) {     nodeToBeRemoved.parentNode.insertBefore(nodeToBeRemoved.firstChild,                                             nodeToBeRemoved); }  nodeToBeRemoved.parentNode.removeChild(nodeToBeRemoved); 

This will move all child nodes to the correct place in the right order.

like image 21
Jonny Buchanan Avatar answered Sep 17 '22 04:09

Jonny Buchanan