glass duo
glass duo

Reputation: 414

Remove certain span tags, keep the text inside - Javascript/jquery

I have the following html:

<h1>These are <span style="color: red;">RED</span> words</h1>
<h2>These are <span class="green">GREEN</span> words</h2>
<h3>These are more <span style="color: red;">RED</span> words</h3>

I want:

<h1>These are RED words</h1>
<h2>These are <span class="green">GREEN</span> words</h2>
<h3>These are more RED words</h3>

In other words, I want to use javascript or jquery to remove the just the <span style="color: red;"></span> but keep everything else. And the span tags have no id, just that style to distinguish them.

Thanks for the help.

Upvotes: 2

Views: 1902

Answers (2)

DannyMoshe
DannyMoshe

Reputation: 6255

This works too:

$('h1').text($('h1').text())
$('h3').text($('h3').text())

Of course you still need logic to test if style exists on the span, just showing there is another way to remove the span and preserve text.

Upvotes: 0

Gerard Cuadras
Gerard Cuadras

Reputation: 1654

You could use unwrap(). Here you can find the documentation. Also remember to check if the span has the property style.

$('h1, h2, h3').find('span').each(function(){
    if($(this).attr('style')){
      $(this).contents().unwrap();
    }
})   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>These are <span style="color: red;">RED</span> words</h1>
<h2>These are <span class="green">GREEN</span> words</h2>
<h3>These are more <span style="color: red;">RED</span> words</h3>

Upvotes: 8

Related Questions