2

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.

1
  • Do you only want to remove span tags that have a style="color: red" or do you want to remove span tags that have any style inlined? Or do you want to remove span tags that have a style inlined with no class? Commented Mar 7, 2018 at 1:34

2 Answers 2

8

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>

Sign up to request clarification or add additional context in comments.

3 Comments

that's a good thing to know, but how would you select the text content in order to match the parent?
Nice! Maybe put in an if statement for .css ('color')
@Jtbs, yes, just added it. Thx
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.