Brana Brana - 5 months ago 6x
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.


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>.