Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to replace multiple HTML nodes

I'm building an e-mail constructor and when the user saves the template I just send the HTML to the server. But I need to remove the drap & drop element to send it to the server.

I'm not very good with DOM manipulation so I don't know where to start from.

This is my HTML:

<table>
  <tbody>
    <tr>
      <th>
        <div class="components-drop-area">
          <p>aa</p>
          <p>bb</p>
        </div>
      </th>
    </tr>
    <tr>
      <th>
        <div class="components-drop-area">
          <p>cc</p>
          <p>dd</p>
        </div>
      </th>
    </tr>
  </tbody>
</table>

I need to remove all the .components-drop-area divs. Something like that:

<table>
  <tbody>
    <tr>
      <th>
        <p>aa</p>
        <p>bb</p>
      </th>
    </tr>
    <tr>
      <th>
        <p>cc</p>
        <p>dd</p>
      </th>
    </tr>
  </tbody>
</table>

I stopped my code here:

var table = document.querySelector('table').cloneNode(true)

let dropAreas = table.querySelectorAll('.components-drop-area')

console.log(table, dropAreas)

How can I loop and remove desired elements while retaining their content?

like image 625
Caio Kawasaki Avatar asked Oct 15 '25 18:10

Caio Kawasaki


1 Answers

One way would simply be to replace the parentNode's innerHTMLs with the .components-drop-area innerHTMLs:

let dropAreas = document.querySelectorAll('.components-drop-area');
for (let i = 0; i < dropAreas.length; i++) {
  dropAreas[i].parentNode.innerHTML = dropAreas[i].innerHTML;
}

// The <div> contents have now been extracted, and the <div> elements removed
console.log(document.querySelector('table').innerHTML);
<table>
  <tbody>
    <tr>
      <th>
        <div class="components-drop-area">
          <p>aa</p>
          <p>bb</p>
        </div>
      </th>
    </tr>
    <tr>
      <th>
        <div class="components-drop-area">
          <p>cc</p>
          <p>dd</p>
        </div>
      </th>
    </tr>
  </tbody>
</table>
like image 107
Obsidian Age Avatar answered Oct 17 '25 09:10

Obsidian Age



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!