holian
holian

Reputation: 755

How to remove div tag content?

How can I remove the content of a div tag using JavaScript?

I have tried some code, but it only removes the level1 div (and of course all o it childern), but how can I remove only the content in level3 inside?

function destroyDiv() {
  var div = document.getElementById("level1");
  div.parentNode.removeChild(div);
}
<div id="level1">

  <div id="level2">

    <div id="level3">
      <label> Test content </label>
    </div>

  </div </div>

  <div id=blahDiv>Remove me</div>
  <input type=button value='Remove the div' onclick='destroyDiv()'>

Upvotes: 13

Views: 68347

Answers (6)

Ray Toal
Ray Toal

Reputation: 88378

While setting the innerHTML property to "" works, a more DOM-ish solution to remove all of the content of a div is to use replaceChildren:

div.replaceChildren()

Upvotes: 0

user11590849
user11590849

Reputation:

(() => { 
          'use strict';
          let needle = 'level3';
          if ( needle === '' || needle === '{{1}}' ) {
              needle = '.?';
          } else if ( needle.slice(0,1) === '/' && needle.slice(-1) === '/' ) {
              needle = needle.slice(1,-1);
          } else {
              needle = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
          }
          needle = new RegExp(needle);
          const divnode = ev => {
                                        if (ev) { window.removeEventListener(ev.type, divnode, true); }
                                    try {
                                            const divs = document.querySelectorAll('div');
                                            for (const div of divs) {
                                                    if (div.outerHTML.match(needle)) {
                                                                    div.remove();
                                                    }           
                                            }
                                    } catch(ex) {
                                        }
          };
          if (document.readyState === 'loading') {
                   window.addEventListener('DOMContentLoaded', divnode, true);
          } else {
                   divnode();
          }
})();

There you go. A dedicated div-remover with RegEx support.

Upvotes: 1

&#199;ağdaş
&#199;ağdaş

Reputation: 1023

Why don't you access directly level3 ?

   document.getElementById("level3").innerHTML = "";

Upvotes: 6

Billy
Billy

Reputation: 15706

You can use:

document.getElementById("level3").innerHTML = "";

Upvotes: 2

DanielB
DanielB

Reputation: 20230

This sould work document.getElementById("level3").innerHTML = ''; but try thinking about using jQuery, because .innerHTML implementation differs in some browsers. jQuery would look like $('#level3').html('');

Upvotes: 27

Harry Joy
Harry Joy

Reputation: 59660

How about this?

var div = document.getElementById("level3");
div.innerHTML = "";

Upvotes: 1

Related Questions