在带有跨度的标题中包装特定单词而不会丢失html格式

时间:2018-04-26 14:53:38

标签: javascript jquery html

我正在尝试使用以下内容将fubar的所有实例包含在任何带有span的标题中:

jQuery('h1, h2, h3, h4, h5, h6').each(function(){
        var located = jQuery(this).text().replace(/fubar/g,"<span class='myspan'>fubar</span>");
        jQuery(this).html(located);
    });

如果文本直接位于H标记内,则可以正常工作,例如

<h1>this is fubar</h1>

但是,如果文本包含在a标记内,则a标记会被删除,例如。

<h1><a href="#">this is fubar</a></h1>

变为:

<h1>this is <span class="myclass">fubar</span></h1>

如何保留a标记和/或其他包装元素?

修改

有时,&#39; fubar&#39;也可能在href属性中。这显然不应该被取代。 E.g。

<h1><a href="#/this-is-fubar">this is fubar</a></h1>

2 个答案:

答案 0 :(得分:2)

使用html()获取元素的内部HTML并替换其中的实例:

$('h1, h2, h3, h4, h5, h6').each(function() {
  var located = $(this).html().replace(/fubar/g, "<span class='myspan'>fubar</span>");
  $(this).html(located);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1><a href="#">this is fubar</a></h1>

答案 1 :(得分:1)

一个选项是find :contains(fubar)所有jQuery('h1, h2, h3, h4, h5, h6').each(function() { jQuery(this).find(':contains(fubar)').each(function(){ var located = $(this).text().replace(/fubar/g, "<span class='myspan'>fubar</span>"); $(this).html(located) }); });的孩子并循环播放并更改文字。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1><a href="#">this is fubar</a></h1>
Intent intent = new Intent ();
intent.putString("name", "Your Name");
 setResult(RESULT_OK,intent);
 onBackPressed();