Select and highlight a single word

自古美人都是妖i 提交于 2019-12-21 19:51:30

问题


I'm trying to select a single word, then apply something to it. Example as below.

<p>Some text here</p>

Is there a way to select the word text, then apply something to it? For example .css() - I know you can select the whole text, then select word number 2, but that's not what I'm trying to do. The word could be many places.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19621917/select-and-highlight-a-single-word

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