Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If element contains certain text

$('.test').css('background','red');

<div id="example">Some text</div>

How can I .addClass('test') if #example contains the word "text"?

like image 721
UserIsCorrupt Avatar asked Apr 26 '12 08:04

UserIsCorrupt


People also ask

How do you check if an element has a string?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do you check includes in HTML?

The contains() method returns true if a node is a descendant of a node. The contains() method returns false if not.


2 Answers

just use :contains pseudoclass

$('#example:contains("text")').addClass('test');

this will add the class to #example if it contains 'text'

like image 185
Fabrizio Calderan Avatar answered Oct 14 '22 17:10

Fabrizio Calderan


You can use $("#example") to get a jQuery wrapper for the element, then use text() to get its text, and use String#indexOf, e.g.:

var ex = $("#example");
if (ex.text().indexOf("text") !== -1) {
    ex.addClass("test");
}

You can also use :contains("text") in the selector as F. Calderan shows, although note that when you use non-standard pseudo-selectors like that, jQuery can't use the underlying browser's built-in stuff for finding elements, so it can be slower. The above will allow jQuery to use document.getElementById. There are only a few situations where the speed really matters, though.

like image 33
T.J. Crowder Avatar answered Oct 14 '22 18:10

T.J. Crowder