Brana Brana - 1 year ago 44
Javascript Question

Javascript remove one html tag with a specific structure

I can remove all html tags from the text but I cannot remove just the structure in span tags with data-word inside ...

function strip(html)
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";

Original is:

I <span data-word="word1" class="synonyms" title="word2">word3</span> <b>word4<b>.

The result should be:

I word3 <b>word4</b>.

With the script from above the result I get is:I word3 word4. So the remaining html is not preserved.

It is code from Strip HTML from Text JavaScript.

Answer Source

Select the elements you want to remove, replace them by their inner HTML and take the inner HTML.

function stripDataWordTags(container) {
  var node = container.cloneNode(true);"synonyms"))
    .forEach(function(a, i) {
      a.parentElement.insertBefore(document.createTextNode(a.innerHTML), a);
  return node.innerHTML;

// Demo and usage:
<div id="test">
  I <span data-word="test" class="synonyms">love</span> <b>ECMAScript 5</b>.