-1

If I had the following html:

<div id="main">
    This <span class="class-two">is</span> a <span class="class-one">string</span> and I want <span class="class-one">to remove</span> spans <span>with the</span> class class-one.
</div>

How would I remove all spans that have the class class-one?

The expected output from the above html would be:

<div id="main">
    This <span class="class-two">is</span> a string and I want to remove spans <span>with a</span> class
</div>

The class-two and the span without a class haven't been removed.

I also need to save the new html string into a variable which is the part I am struggling with.

Something like this: var html = $('#main').$('.class-one').replaceWith((i, txt) => txt);

Dan
  • 103
  • 1
  • 13

1 Answers1

1

Select #main, and find .class-one. Use .replaceWith() with a function to replace with the text. Then use .end() to return to .main and get the .html():

const result = $('#main')
                   .find('.class-one')
                   .replaceWith((i, txt) => txt)
                   .end()
                   .html();

console.log(result);
.class-one {
  color: red;
}

.class-two {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  This <span class="class-two">is</span> a <span class="class-one">string</span> and I want <span class="class-one">to remove</span> spans <span>with the</span> class class-one.
</div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209