How do I remove all of the nested span tags within a span tag in javascript?

Viewed 22

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.

2 Answers

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.

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

Related