Simon Suh Simon Suh - 4 months ago 12
jQuery Question

How do I apply css to an element only if it has certain text content in it using jQuery?

http://jsfiddle.net/aWp2g/2/

css

.highlight {
color: yellow;
}


html

<div>fox</div>
<div>brown</div>


jQuery

if ($('div').text() == 'fox') {
this.addClass('highlight');
}


My above code is not working, I want it to add a class to the element containing a certain text so that it applies a highlighting css.

Answer

this in your code refers to window object. .text() method returns text content of all the selected elements, the returned value is: foxbrown which is not equal to fox.

You can use :contains selector for selecting elements that contain a specific text:

$('div:contains(fox)').addClass('highlight');

Exact match:

$('div').filter(function() {
   return (this.textContent || this.innerText) === 'fox';
}).addClass('highlight');