简体   繁体   中英

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); Array.prototype.slice.call(node.getElementsByClassName("synonyms")) .forEach(function(a, i) { a.parentElement.insertBefore(document.createTextNode(a.innerHTML), a); a.parentElement.removeChild(a); }); return node.innerHTML; } // Demo and usage: alert(stripDataWordTags(document.getElementById("test"))); 
 <div id="test"> I <span data-word="test" class="synonyms">love</span> <b>ECMAScript 5</b>. </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM