简体   繁体   English

删除某些span标签,将文本保留在里面-Javascript / jquery

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

I have the following html: 我有以下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. 换句话说,我想使用javascript或jquery删除<span style="color: red;"></span>但保留其他所有内容。 And the span tags have no id, just that style to distinguish them. 而且span标签没有id,只有那种风格可以区分它们。

Thanks for the help. 谢谢您的帮助。

You could use unwrap() . 您可以使用unwrap() Here you can find the documentation. 在这里可以找到文档。 Also remember to check if the span has the property style . 还记得检查span是否具有属性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. 当然,您仍然需要逻辑来测试跨度上是否存在样式,只是显示出另一种删除跨度并保留文本的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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