简体   繁体   中英

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.

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM