Reputation: 2121
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
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
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