1

Possible Duplicate:
Find text string in jQuery and make it bold

How can I use the jQuery :contains(some text) selector but only select "some text" from "this is some text"?

I have something like this:

<div class="search">this is some text</div>

I am currently using code like this:

$("div.search:contains(some text)").css("text-decoration","underline");

But that underlines "this is some text" and I want it to only underline "some text".

How can I accomplish that most simply?

Community
  • 1
  • 1
webmagnets
  • 2,266
  • 3
  • 33
  • 60
  • 1
    Nop, can't do it this way, need some regex magic at least, check out http://stackoverflow.com/questions/9794851/find-text-string-in-jquery-and-make-it-bold/9795091#9795091 – elclanrs Jan 06 '13 at 03:20
  • You are applying the css to the div - not the text, so the behaviour is correct. You could split the `.html()` and wrap a `` with the desired style around it. – Nic Jan 06 '13 at 03:24

2 Answers2

2

You'll have to use a regex to wrap the inner text with its own element:

$('div.search:contains(some text)').html(function (i, v) {
    return v.replace('some text', '<span>some text</span>');
})
.find('span').css('text-decoration', 'underline');

Use this only if there are no nested elements within div.search. If there are, then this is an entirely different ball game.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

You could rip apart something like the jQuery highlight plugin to to find how they do it. Or you could use the plugin as is and just modify the applied css class to include your underlining rather than the yellow background-color.

Doesn't necessarily answer the question, but if you're going for functionality rather than learning... don't reinvent the wheel.

http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

BZink
  • 7,687
  • 10
  • 37
  • 55
  • This is _almost_ exactly what I need. After I click another word I need the second word to be highlighted and I need the first word to stay highlighted. – webmagnets Jan 06 '13 at 03:53
  • just don't call removeHighlight() and you can highlight as many different words as you want. – BZink Jan 06 '13 at 04:02