0

I want to remove all the text and just get the html structure of a node as a string.

This is my node,

<div class='myparent'>
        <div>
            <div class="pdp-product-price test" id="lll">
                <span> 650 rupees</span>
                <div class="origin-block">
                    <span> 1,500 rupees</span>
                    <span>-57%</span>
                </div>
            </div>
        </div>
    </div>

And what I want is something like this,

<div class='myparent'>
    <div>
        <div class="pdp-product-price test" id="lll">
            <span></span>
            <div class="origin-block">
                <span></span>
                <span></span>
            </div>
        </div>
    </div>
</div>

I tried,

$('.myparent').children().empty(); 

and

$('.myparent').children().text('');

But unfortunately they removed all children.

vimuth
  • 5,064
  • 33
  • 79
  • 116

1 Answers1

1

You can get all text nodes and then .remove() each of them:

function nativeTreeWalker(parent) {
  var walker = document.createTreeWalker(
    parent,
    NodeFilter.SHOW_TEXT,
    null,
    false
  );

  var node;
  var textNodes = [];

  while (node = walker.nextNode()) {
    textNodes.push(node);
  }
  return textNodes;
}

const parent = document.querySelector('.myparent');
nativeTreeWalker(parent).forEach(node => node.remove());
console.log(parent.outerHTML);
<div class='myparent'>
  <div>
    <div class="pdp-product-price test" id="lll">
      <span> 650 rupees</span>
      <div class="origin-block">
        <span> 1,500 rupees</span>
        <span>-57%</span>
      </div>
    </div>
  </div>
</div>

If you don't want to mess with the existing HTML, clone the parent first.

function nativeTreeWalker(parent) {
  var walker = document.createTreeWalker(
    parent,
    NodeFilter.SHOW_TEXT,
    null,
    false
  );

  var node;
  var textNodes = [];

  while (node = walker.nextNode()) {
    textNodes.push(node);
  }
  return textNodes;
}

const parent = document.querySelector('.myparent').cloneNode(true);
nativeTreeWalker(parent).forEach(node => node.remove());
console.log(parent.outerHTML);
<div class='myparent'>
  <div>
    <div class="pdp-product-price test" id="lll">
      <span> 650 rupees</span>
      <div class="origin-block">
        <span> 1,500 rupees</span>
        <span>-57%</span>
      </div>
    </div>
  </div>
</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320