pruett
pruett

Reputation: 2121

Use jQuery .filter() to select specific text within div

HTML:

<p class="greeting">
  hello, my name is kevin. what's yours?
</p>

jQuery:

$("p.greeting").filter(function (){
  return $this.text() === "my name is";
}).css("background", "green");

I'm trying to isolate the words "my name is" in the <p class="greeting"> tag. Can anyone help me with the jQuery as it doesn't seem to work. Thanks.

Upvotes: 6

Views: 6514

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185933

Here you go:

CSS:

.highlight { background-color: yellow; }

JavaScript:

var text = 'My namE iS';

$( 'p.greeting' ).html( function ( i, html ) {
    var regexp, replacement;

    regexp = RegExp( '(' + text + ')', 'gi' );
    replacement = '<span class="highlight">$1</span>';

    return html.replace( regexp, replacement );
});

Live demo: http://jsfiddle.net/SGCDS/5/

Upvotes: 8

Tobias Golbs
Tobias Golbs

Reputation: 4616

You're function returns always false. Only if there is exactly "my name is" in your div, it will return true.

Try something like this:

return $(this).text().indexOf("my name is") != -1;

Upvotes: 1

Related Questions