Select and highlight a single word

只愿长相守 提交于 2019-12-04 15:21:49

Find <p> and children, filter their contents and search for a textual nodeType:

var word = 'text';

var rgx = new RegExp('\\b('+word+')\\b', 'ig');

$('p, p *').contents().filter(function() {
  return this.nodeType === 3;
}).each(function() {
  $(this).replaceWith($(this).text().replace(rgx, '<span class="extra">$1</span>'));
});
.extra{
  background:gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Some text and a link <a href="text.html">text.html</a> here and <b>some bold text there</b>. Text Is Uppercase.<br>Text... text.<br>  Textual.</p>

I believe the above should be quite promising since it'll not crash the HTML since it doesn't matches attributes strings.

You can't select a word, as it is not an element.

To make it possible, you will have to wrap your words in spans.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!