Simon Suh Simon Suh - 5 months ago 15
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.


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';