3

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.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Lemvig Kiggeren
  • 317
  • 1
  • 3
  • 13

3 Answers3

3

Find the target Element and its 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="highlight">$1</span>'));
});
.highlight {
  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.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
-1

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.

MightyPork
  • 18,270
  • 10
  • 79
  • 133
-1

As per my understanding; you want to play with a single word in in a sentence.

<p>This a <span style="color:blue">sample</span> paragraph.</p>