问题
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