Simon Suh Simon Suh - 1 year ago 71
jQuery Question

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


.highlight {
color: yellow;




if ($('div').text() == 'fox') {

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 Source

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:


Exact match:

$('div').filter(function() {
   return (this.textContent || this.innerText) === 'fox';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download