I have innerHTML that looks like this:
<span class="test"> <span> </span> Hello I am here <span class="test1"> </span> </span>
I want to remove all of the nested span tags so that I get this:
<span class="test"> Hello I am here </span>
I have tried using .replace('', '').replace('', '') in but would have to check the last span somehow and also there could be different spans that are dynamically being made from google docs so it would be better if I could do a replace on all of the spans that is not the first or last span.
Try This
$('.test').find('span').remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="test"> <span>dummy data </span> Hello I am here <span class="test1"> dummay data</span> </span>
You can do this by setting the outer span's textContent to it's own textContent - because reading an element's textContent doesn't return any markup tags intersperse with the text.
Resetting textContent also avoids the content of text being parsed by the HTML parser, as it would if used to set the outer element's innerHTML property.
"use strict";
let testSpan = document.querySelector(".test");
testSpan.textContent = testSpan.textContent;
console.log( testSpan.outerHTML);
<span class="test"><span> </span> Hello I am here <span class="test1"> </span> </span>
If you wanted to you could replace consecutive whitespace characters witha single space character before assigning back textContent.
This will work
"use strict";
const elm = document.querySelector(".test");
elm.innerHTML = elm.innerText;
console.log(elm.outerHTML);
<span class="test"><span> </span> Hello I am here <span class="test1"> </span> </span>