Just as the title suggests, lets consider the following html snippet:
<html>
<body>
<div>foo <span>text </span>bar</div>
</body>
</html>
I would like to transform it by removing the span tags, but keeping the text they contain in the same location, such as
<html>
<body>
<div>foo text bar</div>
</body>
</html>
I would like to do that in javascript. Because this task is (I suppose) uncommon (I am in fact trying to build a GUI for marking data for NLP) I could not really find a solution browsing SO or Google... And I am very new to javascript so I didn't really know where to start.
Aditional question: If one know how to resolve the first question, maybe can quickly mention how to perform the same transformation on all document span, such as the following document:
<html>
<body>
<div>foo <span>text </span>bar</div>
<div>foo1 <span>text1 </span>bar1</div>
</body>
</html>
becomes
<html>
<body>
<div>foo text bar</div>
<div>foo1 text1 bar1</div>
</body>
</html>
Thx
You can change the outerHTML
of <span>
to its innerHTML
var elms = document.querySelectorAll('div *'); elms.forEach(e => e.outerHTML = ` ${e.innerHTML} `) //just to test the effect. document.querySelectorAll('div').forEach(x => console.log(x.outerHTML))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>foo<span>text</span>bar</div> <div>foo1<span>text1</span>bar1</div>
Use replace
:
let div = document.getElementById("myDiv"); div.innerHTML = div.innerHTML.replace("<span>", " ").replace("</span>", " ");
span { color: red; }
<div id="myDiv">foo<span>text</span>bar</div>
You can do like this
$(document).ready(function(){
$("div").each(function(index,item){
$(item).html($(item).html().replace(/<\/?span[^>]*>/g,""));
})
})
$(document).ready(function(){ $("div").each(function(index,item){ $(item).html($(item).html().replace(/<\\/?span[^>]*>/g,"")); }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>foo <span>text</span> bar</div> <div>foo1 <span>text1</span> bar1</div>
Simplest way would be to change innerHtml to innerText (if you want to get rid of all inner tags):
var divs = document.querySelectorAll('div'); for (i = 0; i < divs.length; i++) { divs[i].innerHTML = divs[i].innerText; }
span {color:red;}
<div>foo <span>text </span>bar</div> <div>foo1 <span>text1 </span>bar1</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.